Example #1
0
    def getTechsLevel(self, TechCategory, TimeStamp=None):
        '''获取玩家的科技等级'''
        #author:zhoujingjiang
        #TechCategory - 1兵种,2内政
        
        TimeStamp = TimeStamp if TimeStamp else time.time()
        TechsLevel = self.db.out_rows('tb_book_tech', 
                        ['TechType', 'TechLevel', 'LastEndTime'], 
                        'UserId=%s AND TechCategory=%s' % (self.uid, TechCategory))           
        
        TechsDic = dict([(tech['TechType'], 
            tech['TechLevel'] if tech['LastEndTime']<TimeStamp else tech['TechLevel']-1) 
            for tech in TechsLevel])
        
        if TechCategory == 1:
            Techs = {}
            SoldierCfg = Gcore.getCfg('tb_cfg_soldier')
        
            MaxSortLevel = {}
            for tech in TechsDic:
                MaxSortLevel[SoldierCfg[tech]['SoldierSort']] = max(TechsDic[tech], 
                            MaxSortLevel.get(SoldierCfg[tech]['SoldierSort'], 0))
            for soldier in SoldierCfg:
                if SoldierCfg[soldier]['SoldierSide'] != 4:
                    Techs[soldier] = TechsDic.get(soldier, 0)
                else:
                    Techs[soldier] = MaxSortLevel.get(SoldierCfg[soldier]['SoldierSort'], 0)
            return Techs

        else:
            TechTypes = [typ for typ, _ in Gcore.getCfg('tb_cfg_tech_inter')]          
            for TechType in TechTypes:
                TechsDic.setdefault(int(TechType), 0)
            return TechsDic
Example #2
0
    def getWallGeneralList(self):
        '''获取布防武将列表  参考getWallGeneralList()  
        @call: WallUI
        @author: by Lizr
        '''
        kLeader = Gcore.loadCfg(Gcore.defined.CFG_BATTLE)["kLeaderAddNum"]
        SoldierTechs =  Gcore.getMod('Book',self.uid).getTechsLevel(1)
        
        InListGeneral = self.db.out_list('tb_wall_general','GeneralId',"UserId=%s"%self.uid) #已布防
        
        fields = ['GeneralId','GeneralType','GeneralLevel','ForceValue',
                  'WitValue','SpeedValue','LeaderValue','TakeType','TakeTypeDefense']
        rows = Gcore.getMod('General',self.uid).getMyGenerals(fields)
        #Gcore.printd( rows )
        GeneralList = []
        for row in rows:
            if not row['TakeTypeDefense']:
                row['TakeTypeDefense'] = row['TakeType']

            row['Skill'] = Gcore.getCfg('tb_cfg_general',row['GeneralType'],'SkillId')
            SoldierType = row['TakeTypeDefense']
            SoldierLevel = SoldierTechs.get( SoldierType )
            row['SoldierType'] = SoldierType
            row['SoldierLevel'] = SoldierLevel
            key = (SoldierType,SoldierLevel)
            SoldierNum = row['LeaderValue']*kLeader
            
            cfg_soldier = Gcore.getCfg('tb_cfg_soldier_up',key)
            if cfg_soldier:
                #row['Life'] = cfg_soldier['Life']* row['LeaderValue']*kLeader
                #row['Attack'] = cfg_soldier['Attack']*row['LeaderValue']*kLeader
                #row['Denfense'] = cfg_soldier['Defense']
                
                row['Life'] = F.getArmyLife(cfg_soldier['Life'], SoldierNum)
                row['Attack'] = F.getArmyAttack(
                                               generalType = row['GeneralType'],
                                               soldierType = row['SoldierType'],
                                               landForm = 4,
                                               soldierAttack = cfg_soldier['Attack'],
                                               soldierNum = SoldierNum,
                                               forceValue = row['ForceValue'],
                                               )
                row['Denfense'] = F.defenseAdd( cfg_soldier['Defense'],row['SpeedValue'],row['GeneralType']) 
            else:
                row['Life'] = 0
                row['Attack'] = 0
                row['Denfense'] = 0
                
            row['InWall'] = row['GeneralId'] in InListGeneral #是否在布防中
            
#            del row['ForceValue']
#            del row['WitValue']
#            del row['SpeedValue']
#            del row['LeaderValue']
            
            del row['TakeType']
            del row['TakeTypeDefense']
           
            GeneralList.append(row)
        return GeneralList
Example #3
0
 def canAddInBag(self, goodsList):
     '''判断物品列表是否能够全部添加到当前玩家的背包@qiudx
        @goodsList: [{'GoodsType':xxx, 'GoodsId': xxx, 'GoodsNum': xxx},]
        @返回True or False
     ''' 
     needNum = 0 #统计添加物品列表所需的格子数
     tmpGoodsList = copy.deepcopy(goodsList)
     goods = self.db.out_rows(self.tb_bag(), ['*'], 'UserId=%s'%self.uid)
     for tmpGoods in tmpGoodsList:
         if tmpGoods['GoodsType'] in (1, 4, 5):  #装备,兵书,宝物一个格子只能放一件
             equipMod = Gcore.getMod('Equip', self.uid)
             cfgTable = equipMod.getCfgEquipTB(tmpGoods['GoodsType'])
             equipCfg = Gcore.getCfg(cfgTable, tmpGoods['GoodsId'])
             if not equipCfg:
                 continue
             needNum += tmpGoods['GoodsNum']
         elif tmpGoods['GoodsType'] == 2:        #道具可能一个格子放多个
             itemCfg = Gcore.getCfg('tb_cfg_item', tmpGoods['GoodsId'])
             if not itemCfg:
                 continue
             avlNum = int(itemCfg.get('OverlayNum', 1))
             for good in goods:
                 if good['GoodsType'] == 2 and good['GoodsId'] == tmpGoods['GoodsId']:
                     tmpGoods['GoodsNum'] -= avlNum - good['GoodsNum']
                     if tmpGoods['GoodsNum'] <= 0:
                         break
             needNum += int(math.ceil(float(tmpGoods['GoodsNum']) / avlNum))
     
     maxNum = self.getBagSize()#查询背包容量
     avlBag = self._getAvlInBag(goods, maxNum)#查询可用的格仔
     if len(avlBag) >= needNum:
         return True
     return False
Example #4
0
 def GetActivitiesUI(self, param={}):
     '''返回参数1首次充值2签到3成长奖励4活跃度礼包5鸿运当头6在线奖励'''
     optId = 23001
     activities = Gcore.getCfg('tb_cfg_act')
     data = {}
     acts = []
     for act in activities:
         if activities[act]['Status'] == 1:
             actId = activities[act]['ActivityId']
             if actId == 1:#首冲活动
                 playerMod = Gcore.getMod('Player',self.uid)
                 vipTotalPay = playerMod.getUserBaseInfo(['VipTotalPay']).get('VipTotalPay')
                 if vipTotalPay:
                     giftState = self.mod.getGift(1, 0, ['isGet']).get('isGet')
                     data['Recharged'] = 1 if giftState == 0 else 0
                 else:
                     data['Recharged'] = 1 #新号要显示首冲活动
                     
                 if not data['Recharged']: #1表示可以领首冲礼包或者新号显示首冲活动,0表示不显示
                     continue
             elif actId == 5:
                 luckyLog = self.mod.getLuckLog()
                 luckyLog['AwardId'] += 1
                 goodLuckCfg = Gcore.getCfg('tb_cfg_act_lucky_award', luckyLog['AwardId'])
                 if not goodLuckCfg:
                     continue
             acts.append(actId)
     data['Activities'] = acts
     return Gcore.out(optId, data)
Example #5
0
    def randomName(self, icon):
        '''随机名称  '''
        SelectNum = 30
        if icon > 2:
            sex = 2
        else:
            sex = 1
        
        pMod = Gcore.getMod('Player', 1001)

        lastnameList = Gcore.getCfg('tb_cfg_nickname').get(0)
        firstnameList = Gcore.getCfg('tb_cfg_nickname').get(sex)
        lastnameList = random.sample(lastnameList,SelectNum)
        firstnameList = random.sample(firstnameList,SelectNum)

        nicknames=[]
        for i in xrange(SelectNum):
            nickname = lastnameList[i]+firstnameList[i]
            nicknames.append(nickname)

        where = pMod.db.inWhere('NickName',nicknames)
        rows = pMod.db.out_rows('tb_user','NickName',where)
        existNickNames = [r['NickName'] for r in rows]
        notExistNickNames = list(set(nicknames)-set(existNickNames))
        
        NickNames = []
        for NickName in notExistNickNames:
            if Gcore.common.filterInput(NickName,2,16)<0:
                pass #过滤敏感词的名称
            else:
                NickNames.append(NickName)
        
        return NickNames[0]
Example #6
0
    def GetActivitiesUI(self, param={}):
        '''返回参数1首次充值2签到3成长奖励4活跃度礼包5鸿运当头6在线奖励'''
        optId = 23001
        activities = Gcore.getCfg('tb_cfg_act')
        data = {}
        acts = []
        for act in activities:
            if activities[act]['Status'] == 1:
                actId = activities[act]['ActivityId']
                if actId == 1:  #首冲活动
                    playerMod = Gcore.getMod('Player', self.uid)
                    vipTotalPay = playerMod.getUserBaseInfo(
                        ['VipTotalPay']).get('VipTotalPay')
                    if vipTotalPay:
                        giftState = self.mod.getGift(1, 0,
                                                     ['isGet']).get('isGet')
                        data['Recharged'] = 1 if giftState == 0 else 0
                    else:
                        data['Recharged'] = 1  #新号要显示首冲活动

                    if not data['Recharged']:  #1表示可以领首冲礼包或者新号显示首冲活动,0表示不显示
                        continue
                elif actId == 5:
                    luckyLog = self.mod.getLuckLog()
                    luckyLog['AwardId'] += 1
                    goodLuckCfg = Gcore.getCfg('tb_cfg_act_lucky_award',
                                               luckyLog['AwardId'])
                    if not goodLuckCfg:
                        continue
                acts.append(actId)
        data['Activities'] = acts
        return Gcore.out(optId, data)
Example #7
0
    def canAddInBag(self, goodsList):
        '''判断物品列表是否能够全部添加到当前玩家的背包@qiudx
           @goodsList: [{'GoodsType':xxx, 'GoodsId': xxx, 'GoodsNum': xxx},]
           @返回True or False
        '''
        needNum = 0  #统计添加物品列表所需的格子数
        tmpGoodsList = copy.deepcopy(goodsList)
        goods = self.db.out_rows(self.tb_bag(), ['*'], 'UserId=%s' % self.uid)
        for tmpGoods in tmpGoodsList:
            if tmpGoods['GoodsType'] in (1, 4, 5):  #装备,兵书,宝物一个格子只能放一件
                equipMod = Gcore.getMod('Equip', self.uid)
                cfgTable = equipMod.getCfgEquipTB(tmpGoods['GoodsType'])
                equipCfg = Gcore.getCfg(cfgTable, tmpGoods['GoodsId'])
                if not equipCfg:
                    continue
                needNum += tmpGoods['GoodsNum']
            elif tmpGoods['GoodsType'] == 2:  #道具可能一个格子放多个
                itemCfg = Gcore.getCfg('tb_cfg_item', tmpGoods['GoodsId'])
                if not itemCfg:
                    continue
                avlNum = int(itemCfg.get('OverlayNum', 1))
                for good in goods:
                    if good['GoodsType'] == 2 and good['GoodsId'] == tmpGoods[
                            'GoodsId']:
                        tmpGoods['GoodsNum'] -= avlNum - good['GoodsNum']
                        if tmpGoods['GoodsNum'] <= 0:
                            break
                needNum += int(math.ceil(float(tmpGoods['GoodsNum']) / avlNum))

        maxNum = self.getBagSize()  #查询背包容量
        avlBag = self._getAvlInBag(goods, maxNum)  #查询可用的格仔
        if len(avlBag) >= needNum:
            return True
        return False
Example #8
0
 def _getDropShowList(self):
     '''获得高级掉落物品列表,在打战役前显示'''
     showDict = {}
     for k,rows in Gcore.getCfg('tb_cfg_pve_drop').iteritems():
         DropId,Star = k
         
         if DropId not in showDict:
             showDict[DropId] = []
         for row in rows:
             if row['Ratio'] == 0:
                 continue
             row['RewardType'] = int(row['RewardType'])
             if row['RewardType'] in (1,2,4,5,6):
                 cell = {'RewardType':row['RewardType'],'GoodsId':row['GoodsId']}
                 if row['RewardType'] == 1: #装备
                     Quality = Gcore.getCfg('tb_cfg_equip',row['GoodsId'],'Quality')
                     if Quality>=2: #紫装以上
                         if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 elif row['RewardType'] == 2: #道具
                     Quality = Gcore.getCfg('tb_cfg_item',row['GoodsId'],'ItemQuality')
                     if Quality>0: #全掉 
                         if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 else:
                     if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 
         #break
     for DropId in showDict:
         showDict[DropId] =  Gcore.common.list2dict(showDict[DropId])  
     
     return showDict
Example #9
0
    def randomName(self, icon):
        '''随机名称  '''
        SelectNum = 30
        if icon > 2:
            sex = 2
        else:
            sex = 1

        pMod = Gcore.getMod('Player', 1001)

        lastnameList = Gcore.getCfg('tb_cfg_nickname').get(0)
        firstnameList = Gcore.getCfg('tb_cfg_nickname').get(sex)
        lastnameList = random.sample(lastnameList, SelectNum)
        firstnameList = random.sample(firstnameList, SelectNum)

        nicknames = []
        for i in xrange(SelectNum):
            nickname = lastnameList[i] + firstnameList[i]
            nicknames.append(nickname)

        where = pMod.db.inWhere('NickName', nicknames)
        rows = pMod.db.out_rows('tb_user', 'NickName', where)
        existNickNames = [r['NickName'] for r in rows]
        notExistNickNames = list(set(nicknames) - set(existNickNames))

        NickNames = []
        for NickName in notExistNickNames:
            if Gcore.common.filterInput(NickName, 2, 16) < 0:
                pass  #过滤敏感词的名称
            else:
                NickNames.append(NickName)

        return NickNames[0]
Example #10
0
 def checkAndUpdate(self, table):
     '''查找并更新数据库中建筑费用为NULL的数据'''
     fields = ['BuildingId', 'UserId', 'BuildingType', 'BuildingLevel', 'CoinType', 'BuildingPrice', 'LastChangedTime', 'CompleteTime']
     where = ' CoinType is NULL or BuildingPrice is NULL or LastChangedTime is NULL OR CoinType = 0 OR BuildingPrice = 0 '
     tmpRows = self.db.out_rows(table, fields, where)
     if tmpRows:
         for row in tmpRows:
             #print '==PrimaryData:',row
             tmpData = json.dumps(row) + '\n'
             self.fd.write(tmpData)
             if not row['CoinType']:
                 row['CoinType'] = Gcore.getCfg('tb_cfg_building', row['BuildingType'], 'CoinType')
             if not row['BuildingPrice']:
                 row['BuildingPrice'] = Gcore.getCfg('tb_cfg_building_up', (row['BuildingType'], row['BuildingLevel']), 'CostValue')
             if not row['LastChangedTime'] and row['LastChangedTime'] != 0:
                 if row['CompleteTime']:
                     row['LastChangedTime'] = row['CompleteTime'] - Gcore.getCfg('tb_cfg_building_up', (row['BuildingType'], row['BuildingLevel']), 'CDValue')
                 else:
                     row['LastChangedTime'] = 0
                 if row['LastChangedTime'] < 0:
                     row['LastChangedTime'] = 0
             where = 'BuildingId=%s'%row['BuildingId']
             data = {'CoinType': row['CoinType'], 'BuildingPrice': row['BuildingPrice'], 'LastChangedTime': row['LastChangedTime']}
             self.db.update(table, data, where)
             #print '==ModifiedData:',data
             tmpData = json.dumps(data) + '\n'
             self.fd.write(tmpData)
Example #11
0
    def UpgradeClubTech(self,p={}):
        '''
        :升级军团科技
        #todo加一个升级完返回升级后的等级
        '''
        optId = 15076
        techType = p.get('ClubTechType')
        if techType not in range(1,11):
            return Gcore.error(optId,-15076999)#参数错误
        building = self.mod.getClubBuildingInfo()
        if building is None:
            return  Gcore.error(optId,-15076901)#外史院建筑不存在
        clubId = self.mod.getUserClubId()
        if not clubId:
            return Gcore.error(optId,-15076920)#军团不存在
        clubInfo = self.mod.getClubInfo(clubId)
        clubLevel = clubInfo.get('ClubLevel')
        techLevel = self.mod.getClubTechLevel(techType)
        openLevel = Gcore.getCfg('tb_cfg_club_up',clubLevel,'OpenLevelTech'+str(techType))
        if techLevel >= openLevel:
            return Gcore.error(optId,-15076001)#已达最大等级

        cost = Gcore.getCfg('tb_cfg_club_tech',(techType,techLevel+1),'LearnCost')
        
#         print '科技类型',techType
#         print '科技等级',techLevel
#         print '学习费用',cost
        
        flag = self.mod.payDevote(clubId,cost)#成功返回余额
        if flag<0:
            return Gcore.error(optId,-15076995)#支付失败
        newLevel = self.mod.upgradeClubTech(techType)
        recordData = {'uid':self.uid,'ValType':0,'Val':1,'TechType':techType,'TechLevel':newLevel}#成就记录
        return Gcore.out(optId,{'Left':flag,'ClubTechType':techType,'Level':newLevel},achieve=recordData,mission=recordData)
Example #12
0
    def BuyResource(self, param={}):
        '''商城购买资源'''
        optId = 20002

        classMethod = '%s,%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)

        resSaleId = param['ResSaleId']
        resSaleCfg = Gcore.getCfg('tb_cfg_shop_res_sale', resSaleId)

        coinType = resSaleCfg['CoinType']
        percent = resSaleCfg['AddPercent']

        buildingMod = Gcore.getMod('Building', self.uid)
        maxCoin = buildingMod.cacStorageSpace(coinType)

        modCoin = Gcore.getMod('Coin', self.uid)
        currCoinNum = modCoin.getCoinNum(coinType)

        if percent < 1:
            coinValue = maxCoin * percent  #增加货币

        elif percent == 1:
            coinValue = maxCoin - currCoinNum  #增加货币
            percent = coinValue / maxCoin
            #print 'percent', percent
            resSaleList = Gcore.getCfg('tb_cfg_shop_res_sale')
            resSaleList = filter(
                lambda dic: dic['AddPercent'] <= percent and dic['CoinType'] ==
                coinType, resSaleList.values())
            resSaleCfg = max(resSaleList, key=lambda sale: sale['AddPercent'])


#             print resSaleList
#             resSaleList.sort(key=lambda sale:sale['AddPercent'])
#             if resSaleList:
#                 resSaleCfg=resSaleList.pop()

        else:
            return Gcore.error(optId, -20002001)  #percent错误,大于1

        if currCoinNum + coinValue > maxCoin:
            return Gcore.error(optId, -20002002)  #超过资源上限

        kPrice1 = resSaleCfg['kPrice1']
        kPrice2 = resSaleCfg['kPrice2']
        #支付黄金
        useCoinValue = int(math.ceil(coinValue * kPrice1 * maxCoin**kPrice2))
        re = modCoin.PayCoin(optId, 1, useCoinValue, classMethod, param)

        if re > 0:
            re = modCoin.GainCoin(optId, coinType, coinValue, classMethod,
                                  param)
            if re:
                return Gcore.out(optId, {'Result': re})
            else:
                return Gcore.error(optId, -20002997)  #非法操作
        else:
            return Gcore.error(optId, -20002995)  #支付失败
Example #13
0
    def OnlineLottory(self, param={}):
        '''在线奖励抽奖'''
        optId = 23011
        self.mod.refreashTime()  #更新操作时间
        lastLottery = self.mod.getOnlineLottery()
        #获取可抽奖次数(待)
        #timeCfg = Gcore.getCfg('tb_cfg_act_online_limit')
        timeCfg = Gcore.loadCfg(CFG_ACT_ONLINE_LIMIT)
        dt = lastLottery['DayOnlineTime']
        less = 0
        lottoryNum = len(timeCfg.keys())
        #         for i in range(1, len(timeCfg.values())+1):
        #             if dt >= timeCfg[i]['NeedTime']:
        #                 less += 1
        #                 dt -= timeCfg[i]['NeedTime']
        for i in xrange(1, lottoryNum + 1):
            if dt >= timeCfg[str(i)]:
                less += 1
                dt -= timeCfg[str(i)]
        less -= lastLottery['LotteryCount']
        if less <= 0:
            return Gcore.error(optId, -23011001)  #可抽奖次数不足

        #获取抽到的奖励类型和等级
        typeCfg = Gcore.getCfg('tb_cfg_act_online_type').values()
        typeCfg = filter(lambda dic: dic['Ratio'] != 0, typeCfg)  #暂时不随机到宝物和兵书
        types = []
        level = 3
        typeValue = random.randint(2, 3)  #如果等级是3则在铜钱和军资中随即一个
        for i in range(0, 3):
            theType = common.Choice(typeCfg)
            for j in range(0, len(types)):
                if theType['TypeId'] == types[j]:
                    level -= 1
                    typeValue = theType['TypeId']
                    break
            types.append(theType['TypeId'])

        #进行奖励
        awards = Gcore.getCfg('tb_cfg_act_online_award', (typeValue, level))

        award = random.choice(awards)
        modReward = Gcore.getMod('Reward', self.uid)
        award['Gain'] = modReward.reward(optId, param, award['AwardType'],
                                         award['GoodsId'], award['GoodsNum'])

        #更新在线奖励记录
        lastLottery['AwardId'] = award['AwardId']
        lastLottery['LotteryCount'] += 1
        lastLottery['AwardType'] = award['AwardType']
        lastLottery['GoodsId'] = award['GoodsId']
        lastLottery['GoodsNum'] = award['GoodsNum']
        types = [str(t) for t in types]
        lastLottery['LotteryInfo'] = str.join(',', types)
        self.mod.updateOnlineLottery(lastLottery)
        return Gcore.out(optId, {
            'LotteryInfo': lastLottery['LotteryInfo'],
            'Award': award
        })
Example #14
0
    def HandleApply(self, param={}):
        """处理好友申请"""
        optId = 19003
        timeStamp = param["ClientTime"]
        friendUserIds = param["FriendUserIds"]
        handleType = param["HandleType"]
        recordData = {}  # 任务记录
        if not friendUserIds:
            return Gcore.error(optId, -19003999)  # 参数错误

        if handleType == 0:
            """拒绝添加"""
            # self.mod.updateFriendShip(friendUserIds, self.uid, 0, timeStamp)
            self.mod.refuseApply(friendUserIds, self.uid, timeStamp)
            mailMod = Gcore.getMod("Mail", self.uid)
            nickName = self.mod.getUserInfo("NickName")
            # mailMod.sendMail(friendUserIds, '拒绝好友申请', nickName+'拒绝了你的好友申请', 1)#拒绝好友,调用邮件发送信息给对方
            for toUserId in friendUserIds:
                mailMod.sendSystemMail(toUserId, [], optId, other=[nickName])

        elif handleType == 1:
            """确认添加"""
            # 判断玩家自己的好友数是否已达上限
            uLimitNum = Gcore.getCfg("tb_cfg_friend_limit", self.mod.getUserLevel(), "FriendNumLimit")
            uNowNum = self.mod.countFriend(2)
            if uNowNum >= uLimitNum:
                return Gcore.error(optId, -19003001)  # 好友超过上限
            # 如果对方好友已达上限,则拒绝本次添加请求
            validId = []
            for fid in friendUserIds:
                tmpMod = Gcore.getMod("Friend", fid)
                limitNum = Gcore.getCfg("tb_cfg_friend_limit", tmpMod.getUserLevel(), "FriendNumLimit")
                nowNum = tmpMod.countFriend(2)
                if nowNum >= limitNum:
                    # self.mod.updateFriendShip(fid, self.uid, 0, timeStamp)
                    self.mod.refuseApply(fid, self.uid, timeStamp)
                else:
                    validId.append(fid)

            if len(validId) == 0:
                return Gcore.error(optId, -19003002)
            # 如果玩家添加的好友数多于所能添加的个数,则失败
            if uNowNum + len(validId) > uLimitNum:
                return Gcore.error(optId, -19003001)

            for friendUserId in validId:
                self.mod.insFriendShip(self.uid, friendUserId, 2)
                self.mod.updateFriendShip(friendUserId, self.uid, 2, timeStamp)

                recordData = {"uid": self.uid, "ValType": 0, "Val": 1}
                Gcore.getMod("Mission", friendUserId).missionTrigger(optId)  # 触发被同意好友更新

        else:
            return Gcore.error(optId, -19003999)  # 参数错误

        return Gcore.out(optId, {}, mission=recordData)
Example #15
0
    def EquipStrengthen(self,p={}):
        '''强化装备'''
        optId = 16001
        equipId = p['EquipId']
        generalId = p['GeneralId']
        building = self.mod.getSmithyInfo()
        if not building:
            return Gcore.error(optId,-16001901)#建筑不存在
        buildingId = building['BuildingId']
        equipInfo = self.mod.getEquipInfo(1,equipId)#装备信息
        if not equipInfo or equipInfo['UserId'] != self.uid:
            return Gcore.error(optId,-16001910)#装备不存在
        generalMod = Gcore.getMod('General',self.uid)
        generalInfo = generalMod.getLatestGeneralInfo(GeneralIds=generalId)
        
        if not generalInfo:
            return Gcore.error(optId,-16001001) #武将不存在
        if equipId not in self.mod.getEquipsByGeneral(generalId).values():
            return Gcore.error(optId,-16001004)#武器不在该武将身上
        
        equipType = equipInfo['EquipType']
        equipCfg = Gcore.getCfg('tb_cfg_equip',equipType)#装备配置
        strengthenLimit =  equipCfg.get('StrengthenLimit')
        equipPart = equipCfg.get('EquipPart')
        
        equipLevel = equipInfo.get('StrengthenLevel')
        generalLevel = generalInfo.get('GeneralLevel')
        free = self.mod.getMaxStrength(buildingId)['Available']
        if free == 0:
            return Gcore.error(optId,-16001002)#强化次数不足
        elif equipLevel >= generalLevel or equipLevel>= strengthenLimit:
            return Gcore.error(optId,-16001003)#已达最大等级
        
        equipUpCfg = Gcore.getCfg('tb_cfg_equip_up',(equipLevel+1,equipPart))#装备强化配置
        costType = equipUpCfg.get('StrengthenCostType')
        cost = equipUpCfg.get('CostQuality%s'%equipCfg.get('Quality'))
#         print '==Pre:',cost
        
        #计算内政对强化花费的影响
        interMod = Gcore.getMod('Inter',self.uid)
        cost = interMod.getInterEffect(8,cost)
#         print '===Reday:',cost
        flag = self.coinMod.PayCoin(optId,costType,cost,'EquipUI.EquipStrengthen',p)
        if flag>0:
            strengthData = {'StrengthenLevel':equipLevel+1,
                            'EnhanceForce':equipInfo['EnhanceForce']+equipCfg['GrowForce'],
                            'EnhanceWit':equipInfo['EnhanceWit']+equipCfg['GrowWit'],
                            'EnhanceSpeed':equipInfo['EnhanceSpeed']+equipCfg['GrowSpeed'],
                            'EnhanceLeader':equipInfo['EnhanceLeader']+equipCfg['GrowLeader']
                            }
            self.mod.equipStrengthen(buildingId, equipId,equipType,strengthData)
            generalMod.changeAttr(generalId,equipCfg['GrowForce'],equipCfg['GrowSpeed'],equipCfg['GrowWit'],equipCfg['GrowLeader'])
            recordData = {'uid':self.uid,'ValType':0,'Val':1,'EquipType':equipType,'EquipLevel':equipLevel+1}#成就、任务记录
            return Gcore.out(optId,achieve=recordData,mission=recordData)
        else:
            return Gcore.error(optId,-16001995) #支付失败 
Example #16
0
    def CreateWallDefense(self,p={}):
        '''建造防御工事  Lizr'''
        optId = 92001
        defenseType = int(p['DefenseType'])
        x = p['x']
        y = p['y']
        xSize = p['xSize']
        ySize = p['ySize']
        
        buildingInfo = self.mod.getWallInfo()
        if buildingInfo is None:
            return Gcore.error(optId,-92001998)#非法操作
        wallLevel = buildingInfo.get('BuildingRealLevel')
        
        if defenseType/100 != 2: #200~299
            return Gcore.error(optId,-92001998) #非法操作
        
        Size = Gcore.getCfg('tb_cfg_soldier',defenseType,'Size')
        
        if str(xSize)+'*'+str(ySize)!=Size and str(ySize)+'*'+str(xSize)!=Size: #非配置的尺寸 1*3
            return Gcore.error(optId,-92001001) #尺寸不合法
        
#        if not self.mod.checkWallCoord(x,y): #@todo: 加上布防坐标验证
#            return Gcore.error(optId,-92001002) #坐标不合法
        
        maxCount = Gcore.getCfg('tb_cfg_wall',wallLevel,'DefenseType%s'%defenseType)
      
        defenseNum = self.mod.getDefenseNum()
        
        if defenseNum.get(defenseType,0)>=maxCount:
            return Gcore.error(optId,-92001003) #超出最大可建数量
        bookMod = Gcore.getMod('Book',self.uid)
        coinMod = Gcore.getMod('Coin',self.uid)
        defenseLevel = bookMod.getTechsLevel(1).get(defenseType,0)#从书院获取
        if defenseLevel==0:
            defenseLevel=1
        defenseCfg = Gcore.getCfg('tb_cfg_soldier_up',(defenseType,defenseLevel))
        cost = defenseCfg.get('MakeCost')
        costType = defenseCfg.get('MakeCostType')
        payState = coinMod.PayCoin(optId,costType,cost,'WallUI.CreateWallDefense',p)
#        payState = 1
        if payState:
            data={
                  'UserId':self.uid,
                  'SoldierType':defenseType,
                  'SoldierLevel':defenseLevel,
                  'xSize':xSize,'ySize':ySize,
                  'x':x,'y':y,
                  'MakeCost':cost,
                  }
            DefenseId = self.mod.createDefense(data)
            recordData = {'uid':self.uid,'ValType':0,'Val':1,'Level':defenseLevel}
            return Gcore.out(optId,{'WallDefenseId':DefenseId},mission=recordData)

        else:
            Gcore.error(optId,-92001995) #支付失败
Example #17
0
    def OnlineLottory(self, param={}):
        '''在线奖励抽奖'''
        optId = 23011
        self.mod.refreashTime()#更新操作时间
        lastLottery = self.mod.getOnlineLottery()
        #获取可抽奖次数(待)
        #timeCfg = Gcore.getCfg('tb_cfg_act_online_limit')
        timeCfg = Gcore.loadCfg(CFG_ACT_ONLINE_LIMIT)
        dt = lastLottery['DayOnlineTime']
        less = 0
        lottoryNum = len(timeCfg.keys())
#         for i in range(1, len(timeCfg.values())+1):
#             if dt >= timeCfg[i]['NeedTime']:
#                 less += 1
#                 dt -= timeCfg[i]['NeedTime']
        for i in xrange(1, lottoryNum + 1):
            if dt >= timeCfg[str(i)]:
                less += 1
                dt -= timeCfg[str(i)]
        less -= lastLottery['LotteryCount']
        if less <= 0:
            return  Gcore.error(optId, -23011001)#可抽奖次数不足
        
        #获取抽到的奖励类型和等级
        typeCfg = Gcore.getCfg('tb_cfg_act_online_type').values()
        typeCfg = filter(lambda dic:dic['Ratio']!=0, typeCfg)#暂时不随机到宝物和兵书
        types = []
        level = 3
        typeValue = random.randint(2, 3)#如果等级是3则在铜钱和军资中随即一个
        for i in range(0, 3):
            theType = common.Choice(typeCfg)
            for j in range(0, len(types)):
                if theType['TypeId'] == types[j]:
                    level -= 1
                    typeValue = theType['TypeId']
                    break
            types.append(theType['TypeId'])
        
        #进行奖励
        awards = Gcore.getCfg('tb_cfg_act_online_award', (typeValue, level))
        
        award = random.choice(awards)
        modReward = Gcore.getMod('Reward', self.uid)
        award['Gain'] = modReward.reward(optId, param, award['AwardType'], award['GoodsId'], award['GoodsNum'])
        
        #更新在线奖励记录
        lastLottery['AwardId'] = award['AwardId']
        lastLottery['LotteryCount'] += 1
        lastLottery['AwardType'] = award['AwardType']
        lastLottery['GoodsId'] = award['GoodsId']
        lastLottery['GoodsNum'] = award['GoodsNum']
        types = [str(t) for t in types]
        lastLottery['LotteryInfo'] = str.join(',',types)
        self.mod.updateOnlineLottery(lastLottery)
        return Gcore.out(optId, {'LotteryInfo': lastLottery['LotteryInfo'], 'Award': award})
Example #18
0
    def BuyResource(self, param={}):
        '''商城购买资源'''
        optId=20002

        classMethod = '%s,%s'%(self.__class__.__name__,sys._getframe().f_code.co_name)
        
        resSaleId = param['ResSaleId']
        resSaleCfg = Gcore.getCfg('tb_cfg_shop_res_sale', resSaleId)

        coinType = resSaleCfg['CoinType']
        percent = resSaleCfg['AddPercent']

        buildingMod = Gcore.getMod('Building', self.uid)
        maxCoin = buildingMod.cacStorageSpace(coinType)

        modCoin = Gcore.getMod('Coin', self.uid)
        currCoinNum = modCoin.getCoinNum(coinType)

        if percent < 1:
            coinValue = maxCoin*percent#增加货币
            
        elif percent == 1:
            coinValue = maxCoin - currCoinNum#增加货币
            percent = coinValue / maxCoin
            #print 'percent', percent
            resSaleList = Gcore.getCfg('tb_cfg_shop_res_sale')
            resSaleList = filter(lambda dic:dic['AddPercent'] <= percent and dic['CoinType'] == coinType, resSaleList.values())
            resSaleCfg = max(resSaleList, key=lambda sale:sale['AddPercent'])
#             print resSaleList
#             resSaleList.sort(key=lambda sale:sale['AddPercent'])
#             if resSaleList:
#                 resSaleCfg=resSaleList.pop()
                    
        else:
            return Gcore.error(optId, -20002001)#percent错误,大于1
        
        if currCoinNum + coinValue > maxCoin:
            return Gcore.error(optId, -20002002)#超过资源上限

        kPrice1 = resSaleCfg['kPrice1']
        kPrice2 = resSaleCfg['kPrice2']
        #支付黄金
        useCoinValue = int(math.ceil(coinValue*kPrice1*maxCoin**kPrice2))
        re = modCoin.PayCoin(optId, 1, useCoinValue, classMethod, param)
        
        if re > 0:
            re = modCoin.GainCoin(optId, coinType, coinValue, classMethod, param)
            if re:
                return Gcore.out(optId, {'Result':re})
            else:
                return Gcore.error(optId, -20002997)#非法操作
        else:
            return Gcore.error(optId, -20002995)#支付失败
Example #19
0
 def touchActPoint(self,oldLevel,newLevel):
     '''更新行动力,升级时调用'''
     newLevelPoint = Gcore.getCfg('tb_cfg_action_point',newLevel,'ActPoint')
     oldLevelPoint = Gcore.getCfg('tb_cfg_action_point',oldLevel,'ActPoint')
     diffPoint = newLevelPoint - oldLevelPoint
     if diffPoint:
         row = self._lastActRecord()
         if row:
             todaytime = Gcore.common.today0time()
             sql = "UPDATE tb_war_action SET ActPoint=ActPoint+%s WHERE UserId=%s AND LastWarTime>=%s" \
             %(diffPoint,self.uid,todaytime)
             self.db.execute(sql) #如果今日有打过 就修正累计记录
Example #20
0
    def GetInviteUI(self, param={}):
        """招贤馆:招募界面"""
        optId = 15006

        BuildingId = param["BuildingId"]
        RequestTimeStamp = param["ClientTime"]

        InviteInfo = self.mod.getInvite()
        modBuilding = Gcore.getMod("Building", self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=RequestTimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15006901)  # 用户没有该建筑
        if BuildingInfo["BuildingState"] == 1:
            return Gcore.error(optId, -15006902)  # 建筑正在建造
        if BuildingInfo["BuildingType"] != 13:
            return Gcore.error(optId, -15006903)  # 该建筑不是招贤馆
        BuildingLevel = BuildingInfo["BuildingRealLevel"]

        if not InviteInfo:
            print "第一次招募"
            ChosenGenerals = self.mod.chooseGenerals(GeneralNum=3, IsFirst=True)
            self.mod.insertInvite(ChosenGenerals, BuildingLevel, RequestTimeStamp)
            RemainedTime = Gcore.getCfg("tb_cfg_building_up", key=(13, BuildingLevel), field="RefreshValue")
            return Gcore.out(
                optId, body={"RemainedTime": RemainedTime, "Generals": ChosenGenerals, "CostValue": 5}
            )  # 系统错误 (招募表中此玩家初始记录)

        print "InviteInfo", InviteInfo

        # SpeedCount = self.mod.cacSpeedCount(InviteInfo['SpeedCount'], InviteInfo['LastSpeedDate'], RequestTimeStamp)
        # SpeedCount += 1
        # CostValue = SpeedCount * 2

        CostValue = 5  # 读配置 - 招贤馆每次刷新所用的黄金数量
        RetDic = {}
        RetDic["CostValue"] = CostValue
        if RequestTimeStamp < InviteInfo["EndTime"]:
            RefreshTimeRemained = InviteInfo["EndTime"] - RequestTimeStamp

            RetDic["RemainedTime"] = RefreshTimeRemained
            RetDic["Generals"] = [InviteInfo["GeneralId1"], InviteInfo["GeneralId2"], InviteInfo["GeneralId3"]]

            return Gcore.out(optId, RetDic)
        else:
            RefreshValue = Gcore.getCfg("tb_cfg_building_up", key=(13, BuildingLevel), field="RefreshValue")
            RefreshTimeRemained = RefreshValue - (RequestTimeStamp - InviteInfo["EndTime"]) % RefreshValue
            RefreshTimeStamp = RequestTimeStamp - (RequestTimeStamp - InviteInfo["EndTime"]) % RefreshValue
            ChosenGenerals = self.mod.chooseGenerals()
            self.mod.updateInvite(ChosenGenerals, BuildingLevel, RefreshTimeStamp)

            RetDic["RemainedTime"] = RefreshTimeRemained
            RetDic["Generals"] = ChosenGenerals
            return Gcore.out(optId, RetDic)
Example #21
0
 def _calLevelByCost(self,equipType,currentLevel,cost,levelLimit=None):
     '''根据费用计算装备升级'''
     equipUpCfg = Gcore.getCfg('tb_cfg_equip_up')
     equipCfg = Gcore.getCfg('tb_cfg_equip',equipType)
     eq = equipCfg['Quality']
     ep = equipCfg['EquipPart']
     if levelLimit is None:
         levelLimit = equipCfg['StrengthenLimit']
     toLevelUpCost = equipUpCfg.get((currentLevel+1,ep)).get('CostQuality%s'%eq)
     while currentLevel<levelLimit and cost>=toLevelUpCost:
         currentLevel += 1
         cost -= toLevelUpCost
         toLevelUpCost = equipUpCfg.get((currentLevel+1,ep)).get('CostQuality%s'%eq)
     return (currentLevel,cost)
Example #22
0
 def touchActPoint(self, oldLevel, newLevel):
     '''更新行动力,升级时调用'''
     newLevelPoint = Gcore.getCfg('tb_cfg_action_point', newLevel,
                                  'ActPoint')
     oldLevelPoint = Gcore.getCfg('tb_cfg_action_point', oldLevel,
                                  'ActPoint')
     diffPoint = newLevelPoint - oldLevelPoint
     if diffPoint:
         row = self._lastActRecord()
         if row:
             todaytime = Gcore.common.today0time()
             sql = "UPDATE tb_war_action SET ActPoint=ActPoint+%s WHERE UserId=%s AND LastWarTime>=%s" \
             %(diffPoint,self.uid,todaytime)
             self.db.execute(sql)  #如果今日有打过 就修正累计记录
Example #23
0
    def incGeneralExp(self, General, ExpValue, UserLevel=None, flag=True):
        '''增加武将经验'''
        # 参数
        # + flag - 是否将武将信息更新到武将表
        # + + True - 更新到武将表
        # + + False - 不更新到武将表
        # + General - dict - 武将信息

        if not UserLevel:UserLevel = self.getUserLevel()

        #读配置
        GeneralCfg = Gcore.getCfg('tb_cfg_general')
        GeneralUpCfg = Gcore.getCfg('tb_cfg_general_up')
        MaxLevel = max(GeneralUpCfg.keys()) #武将的最高等级

        #武将基础信息
        GeneralId = General['GeneralId']
        GeneralLevel = General['GeneralLevel']
        GeneralType = General['GeneralType']
        General['ExpValue'] += int(ExpValue)
        
        #判断升级
        for lv in xrange(1, MaxLevel+1, 1):
            if (lv + GeneralLevel > MaxLevel) or (lv + GeneralLevel > UserLevel):
                break

            NxtLvExp = GeneralUpCfg[lv + GeneralLevel]['Exp']
            if NxtLvExp > General['ExpValue']: #经验不够升级
                break

            #改变等级,经验值
            General['ExpValue'] -= NxtLvExp
            General['GeneralLevel'] += 1

            #属性成长
            General['ForceValue'] += GeneralCfg[GeneralType]['GrowForce']
            General['WitValue'] += GeneralCfg[GeneralType]['GrowWit']
            General['SpeedValue'] += GeneralCfg[GeneralType]['GrowSpeed']
            General['LeaderValue'] += GeneralCfg[GeneralType]['GrowLeader']
        
        if flag: #将升级信息写入数据库。
            self.updateGeneralById(General, GeneralId)
            
        if ExpValue: #added by zhangguanghui
            modEvent = Gcore.getMod('Event', self.uid)
            modEvent.generalExpGet(General['GeneralType'], ExpValue)

        return General
Example #24
0
    def UpgradeClubTech(self, p={}):
        '''
        :升级军团科技
        #todo加一个升级完返回升级后的等级
        '''
        optId = 15076
        techType = p.get('ClubTechType')
        if techType not in range(1, 11):
            return Gcore.error(optId, -15076999)  #参数错误
        building = self.mod.getClubBuildingInfo()
        if building is None:
            return Gcore.error(optId, -15076901)  #外史院建筑不存在
        clubId = self.mod.getUserClubId()
        if not clubId:
            return Gcore.error(optId, -15076920)  #军团不存在
        clubInfo = self.mod.getClubInfo(clubId)
        clubLevel = clubInfo.get('ClubLevel')
        techLevel = self.mod.getClubTechLevel(techType)
        openLevel = Gcore.getCfg('tb_cfg_club_up', clubLevel,
                                 'OpenLevelTech' + str(techType))
        if techLevel >= openLevel:
            return Gcore.error(optId, -15076001)  #已达最大等级

        cost = Gcore.getCfg('tb_cfg_club_tech', (techType, techLevel + 1),
                            'LearnCost')

        #         print '科技类型',techType
        #         print '科技等级',techLevel
        #         print '学习费用',cost

        flag = self.mod.payDevote(clubId, cost)  #成功返回余额
        if flag < 0:
            return Gcore.error(optId, -15076995)  #支付失败
        newLevel = self.mod.upgradeClubTech(techType)
        recordData = {
            'uid': self.uid,
            'ValType': 0,
            'Val': 1,
            'TechType': techType,
            'TechLevel': newLevel
        }  #成就记录
        return Gcore.out(optId, {
            'Left': flag,
            'ClubTechType': techType,
            'Level': newLevel
        },
                         achieve=recordData,
                         mission=recordData)
Example #25
0
    def exchangeGeneralCard(self, item_id):
        '''兑换武将卡'''
        # 不满足兑换所需的数量返回False,
        # + 满足兑换所需的数量,减少相应的数量,并返回碎片的当前数量
        table = 'tb_patch'
        where = 'UserId=%s AND ItemId=%s' % (self.uid, item_id)
        #查出碎片数量
        fields = ['Patch1', 'Patch2', 'Patch3', 'Patch4']
        patch_num = self.db.out_fields(table, fields, where)
        if not patch_num:
            return False
        try:
            #从配置中查出所需的碎片数量
            item = Gcore.getCfg('tb_cfg_general_patch', item_id)

            for k in item:
                if k.startswith('PatchNum'):
                    column_name = 'Patch%d' % int(k[-1])
                    patch_num[column_name] -= item[k]  #减少相应的数量
                    if patch_num[column_name] < 0:
                        return False

            #更新数据库
            self.db.update(table, patch_num, where)
            return patch_num
        except Exception:
            return False
        else:
            return True
Example #26
0
    def initRecord(self, building_id, building_type, time_stamp,
                   building_level, complete_time):
        '''向士兵生产表插入一条初始记录'''
        cd_interval = 300  #计算时间间隔

        if complete_time <= time_stamp:
            last_changed_time = time_stamp - (time_stamp -
                                              complete_time) % cd_interval
        else:
            last_changed_time = complete_time

        init_data = {
            'UserId':
            self.uid,
            'BuildingId':
            building_id,
            'BuildingType':
            building_type,
            'StorageNum':
            Gcore.getCfg('tb_cfg_building_up', (building_type, building_level),
                         'MakeValue'),
            'LastChangedTime':
            last_changed_time,
            'LastCalTime':
            time_stamp,
            'CreateTime':
            time_stamp
        }
        self.db.insert(self._soldier_storage, init_data)
        return init_data
Example #27
0
    def calClubTechs(self,clubLevel=None):
        '''
        :通过军团等级计算我的的军团科技信等级
        :实际军团科技等级,没有军团所有军团科技等级为0
        '''
        fields = []
        for i in range(1,11):
            fields.append('TechLevelType'+str(i))
        levels = self.db.out_fields('tb_club_tech',fields,'UserId=%s'%self.uid)
        
        if not levels:#没有军团科技等级记录
            self.db.insert('tb_club_tech',{'UserId':self.uid})
            return self.db.out_fields('tb_club_tech',fields,'UserId=%s'%self.uid)

        #查询军团等级
        if clubLevel is None:
            clubId = self.getUserClubId()
            clubLevel = self.getClubInfo(clubId).get('ClubLevel') if clubId else None
            
        #科技等级不高于军团等级限制
        clubCfg = Gcore.getCfg('tb_cfg_club_up')
        for key in levels:
            techType = int(key[13:])
            if clubLevel == 0 or clubLevel is None:
                levels[key] = 0#没有军团科技等级为0
                continue
                
            openLevel = clubCfg.get(clubLevel,{}).get('OpenLevelTech%s'%techType)
            if levels.get(key)>openLevel:
                levels[key] = openLevel#已学习等级高于军团最高上限时等级为上限
        return levels
Example #28
0
 def getActPoint(self):
     '''获得 剩余行动点数/最大行动点数'''
     BuyActPoint = self.getUserInfo('BuyActPoint')
     row = self._lastActRecord()
     MaxPoint = Gcore.getCfg('tb_cfg_action_point',self.getUserLevel(),'ActPoint')
     if not row:
         RestPoint = MaxPoint + BuyActPoint
     else:
         nowtime = Gcore.common.nowtime()
         PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime',1200)
         if Gcore.TEST and self.uid in [1001,43953]:
             PerIncrTime = testPerIncrTime
         if row['ActPoint']>=MaxPoint: #已满,不恢复
             RestPoint = row['ActPoint']
         else:
             AccuTime = row['AccuTime'] + ( nowtime - row['LastWarTime'] )
             incrTimes = AccuTime//PerIncrTime #回复一点需要多长时间 20分钟
             #print 'incrTimes',incrTimes
             print 'getActPoint.上次剩余',row['ActPoint']
             print 'getActPoint.至已经恢复了',incrTimes
             ActPoint = row['ActPoint'] + incrTimes
             if ActPoint > MaxPoint:
                 ActPoint = MaxPoint
                 print 'getActPoint.剩余+累计越出上限,设为上限',ActPoint
                 
             #查看的时候 不更新累计时间 tb_war_action.AccuTime    
             RestPoint = ActPoint
         
     #print '剩余次数    最大次数',RestPoint,MaxPoint, 前台显示的是: 剩余次数/最大次数
     return (RestPoint,MaxPoint)
Example #29
0
 def exchangeGeneralCard(self, item_id):
     '''兑换武将卡'''
     # 不满足兑换所需的数量返回False,
     # + 满足兑换所需的数量,减少相应的数量,并返回碎片的当前数量
     table = 'tb_patch'
     where = 'UserId=%s AND ItemId=%s' % (self.uid, item_id)
     #查出碎片数量
     fields = ['Patch1', 'Patch2', 'Patch3', 'Patch4']
     patch_num = self.db.out_fields(table, fields, where)
     if not patch_num:
         return False
     try:
         #从配置中查出所需的碎片数量
         item = Gcore.getCfg('tb_cfg_general_patch', item_id)
         
         for k in item:
             if k.startswith('PatchNum'):
                 column_name = 'Patch%d' % int(k[-1])
                 patch_num[column_name] -= item[k] #减少相应的数量
                 if patch_num[column_name] < 0:
                     return False
         
         #更新数据库
         self.db.update(table, patch_num, where)
         return patch_num         
     except Exception: return False
     else: return True
Example #30
0
    def useActPoint(self, point=1):
        '''战役成功,使用一点行动力'''
        BuyActPoint = self.getUserInfo('BuyActPoint')
        if BuyActPoint:
            if BuyActPoint >= point:
                cutPoint = point
                BuyActPoint -= point
            else:  #剩余购买行动力已不够扣减
                cutPoint = BuyActPoint
                #point -= BuyActPoint #剩余部分需在未购买处扣
                BuyActPoint = 0
                print '剩余购买行动力已不够扣减,point:', point
            sql = 'UPDATE tb_user SET BuyActPoint=BuyActPoint-%s WHERE UserId=%s' % (
                cutPoint, self.uid)
            self.db.execute(sql)
            #print '已购买的行动力扣1,剩余',BuyActPoint

        MaxPoint = Gcore.getCfg('tb_cfg_action_point', self.getUserLevel(),
                                'ActPoint')
        row = self.recoverActPoint(point, 0)
        if row:  #今天有打过
            pass
        else:  #今天未打过
            #print '今天未打过'
            row = {}
            row['ActPoint'] = MaxPoint + BuyActPoint
            row['LastWarTime'] = Gcore.common.nowtime()
            res = self.db.update('tb_war_action', row, 'UserId=%s' % self.uid)
            if not res:  #从来没有记录
                row['UserId'] = self.uid
                self.db.insert('tb_war_action', row)
Example #31
0
    def countGoodsNum(self, goodsIds):
        '''获取道具的数量'''
        # author:zhoujingjiang
        # goodsIds - 道具ID 或 道具ID的序列
        # 返回值:如果goodIds是单个道具,返回该道具的数量;否则返回字典。
        item_ids = Gcore.getCfg('tb_cfg_item').keys()

        is_single = False
        if isinstance(goodsIds, (int, long, basestring)):
            is_single = int(goodsIds)
            goodsIds = [goodsIds]

        for goodsId in iter(goodsIds):
            if int(goodsId) not in item_ids:
                raise TypeError('%s is not an item' % goodsId)

        table = self.tb_bag()
        where = 'UserId=%s AND (GoodsId= ' % self.uid
        where += ' OR GoodsId= '.join(map(str, iter(goodsIds))) + ' ) '  
        fields = ['GoodsNum', 'GoodsId']
        items = self.db.out_rows(table, fields, where)
        
        combined = {}
        for item in items:
            combined[item['GoodsId']] = combined.get(item['GoodsId'], 0) \
                        + item['GoodsNum']
        for goodsId in iter(goodsIds):
            combined.setdefault(int(goodsId), 0)

        return combined if not is_single else combined[is_single]
Example #32
0
    def vipAddTotal(self, optId, goldNum):
        '''
        :玩家充值黄金,增加玩家累积黄金,更新Vip等级
        @param goldNum:增加的黄金数量
        '''
        userInfo = self.getUserInfo(['VipLevel', 'VipTotalPay'])
        curLevel = userInfo.get('VipLevel')
        curVipTotal = userInfo.get('VipTotalPay')

        totalPay = goldNum + curVipTotal
        levelCfg = Gcore.getCfg('tb_cfg_vip_up')
        levelUp = max([
            levelCfg[level]['VipLevel'] for level in levelCfg
            if totalPay >= levelCfg[level]['TotalPay']
        ])
        data = {'VipTotalPay': totalPay, 'VipLevel': levelUp}
        self.db.update('tb_user', data, 'UserId=%s' % self.uid)
        if levelUp > curLevel:  #VIP升级
            interMod = Gcore.getMod('Inter', self.uid)
            interMod.updateInterVip()  #更新VIP内政加成
            Gcore.setUserData(self.uid, {'VipLevel': levelUp})  #更新用户缓存  Lizr
            Gcore.push(107, self.uid, {'VipLevel': levelUp})  #推送给前端升级 Lizr
        if curVipTotal == 0:
            #增加首冲奖励
            Gcore.getMod('Activity', self.uid).insertGifts(1, 0)
        #发送系统邮件
        mailMod = Gcore.getMod('Mail', self.uid)
        mailMod.sendSystemMail(self.uid, [], optId, other=[
            goldNum,
        ])

        return levelUp
Example #33
0
 def cacAllTrainSoldierNum(self, time_stamp, queues):
     '''计算某一时刻的产兵量'''
     soldier_spawn = {}
     deletes = [] #征完兵的征兵队列
     remains = {} #每个ProcessId对应的剩余未生产数量
     for _, train_queues in queues.iteritems():
         speed = Gcore.getCfg('tb_cfg_building_up',
                              (6, train_queues[0][1]),
                              'HourValue')
         speed = int(speed / 3600)
         start_time = train_queues[0][2]
         seconds = time_stamp - start_time
         for train_queue in train_queues:
             seconds_need = int(math.ceil(train_queue[0]/(speed+0.0)))
             if seconds >= seconds_need:
                 seconds -= seconds_need
                 soldier_spawn[train_queue[4]] = \
                     soldier_spawn.setdefault(train_queue[4], 0) + train_queue[0]
                 deletes.append(train_queue[3])
             else:
                 soldier_spawn[train_queue[4]] = \
                     soldier_spawn.setdefault(train_queue[4], 0) + int(seconds * speed)
                 remains[train_queue[3]] = train_queue[0] - int(seconds * speed)
                 break
     return soldier_spawn, remains, deletes
Example #34
0
    def getAchievements(self):
        '''
        :获取我的成就
        '''
        result = {}
        fields = ['AchieveType','Finished','NextAchieveId','CurrentAchieve']
        acs = self.db.out_rows('tb_achieve',fields,'UserId=%s'%self.uid)
        achCfgs = Gcore.getCfg('tb_cfg_achieve')
        types = achCfgs.keys()
        
        #查找成就记录中还没有的成就
        for ac in acs:
            acType = ac.get('AchieveType')
            if acType in types:
                types.remove(acType)
            
        #插入还没有初始化的成就数据
        if types: 
            insertRows = []
            for t in types:
#                 firstAchieve = min(achCfgs[t].keys())
                data = {'AchieveType':t,
                        'UserId':self.uid,
                        'NextAchieveId':1}
                insertRows.append(data)
                data['CurrentAchieve'] = 0
                data['Finished'] = 0
                result[t] = data
            self.db.insertmany('tb_achieve',insertRows)
        
        #生成以成就类型为key的字典
        for ac in acs:
            result[ac['AchieveType']] = ac
        return result
Example #35
0
 def openSoliders(self, time_stamp=None, reverse=False):
     '''按照顺序返回玩家已开放的兵种'''
     #reverse-False从低到高,True从高到低
     modBuilding = Gcore.getMod('Building', self.uid)
     Buildings = modBuilding.getBuildingByType(6, TimeStamp=time_stamp)
     Buildings = [
         building for building in Buildings
         if building['BuildingState'] != 1
     ]
     if not Buildings:
         return []
     max_level = max(
         [building['BuildingRealLevel'] for building in Buildings])
     print 'max_level', max_level
     soldier_details = Gcore.getCfg('tb_cfg_soldier').values()
     soldiers = [
         soldier_detail for soldier_detail in soldier_details
         if soldier_detail['OpenLevel'] <= max_level
         and soldier_detail['SoldierClass'] == 1 and (
             soldier_detail['SoldierSide'] == 0
             or soldier_detail['SoldierSide'] == self.getUserCamp())
     ]
     soldiers = sorted(soldiers,
                       key=lambda dic: dic['OpenLevel'],
                       reverse=reverse)
     Techs = Gcore.getMod('Book', self.uid).getTechsLevel(1)
     return [{
         soldier['SoldierType']: Techs.get(soldier['SoldierType'])
     } for soldier in soldiers]
Example #36
0
 def GetSignInLog(self, param={}):
     '''获取签到日志'''
     optId = 23006
     data = self.mod.getSigninLog()
     a = list(data['SignInDate'])
     data['SignInDate'] = ','.join(a)
     #获取全勤奖励信息
     awards = Gcore.getCfg('tb_cfg_act_signin_award').values()
     fullWorkAwards = filter(lambda dic:dic['AwardId']>=3000 and dic['AwardId']<4000, awards)
     now = datetime.datetime.now()
     data['FullWorkAwardId'] = fullWorkAwards[now.month-1]['AwardId']
     #获取周期奖励信息
     finalAwards = Gcore.loadCfg(CFG_ACT_SIGNIN)['FinalAwardId']
     #awards = finalAwards.split(',')
     awards = finalAwards
     signCount = data['SignInCount']
     n = signCount / 30 % len(awards)
     if signCount % 30 == 0:
         n -= 1
     awardId = int(awards[n])
     data['FinalAwardId'] = awardId
     signCount = signCount % 30
     data['SignInDays'] = signCount if signCount else 30 #用于前台显示当前周期内的天数,30天一周期
     data['Refill'] = 5 - data['Refill']
     return Gcore.out(optId, data)
Example #37
0
    def BuyMap(self,p={}):
        '''购买地图'''

        optId = 14002
        if 'x' not in p or 'y' not in p:
            return Gcore.error(optId,-14002001) #非法参数 
        
        x = p['x']
        y = p['y']
        if not self.mod.checkBuyStartCoord(x,y):
            print self.mod.db.sql
            return Gcore.error(optId,-14002002) #所传的坐标非可购买坐标的起点
            
        if self.mod.checkHadBuy(x,y):
            return Gcore.error(optId,-14002003) #你已经购买过此坐标
        
        MapBuyTimes = Gcore.getMod('Player',self.uid).getMapBuyTimes()
        CostValue = Gcore.getCfg('tb_cfg_map_cost',MapBuyTimes,'Cost')
        print CostValue
        #开始支付
        modCoin = Gcore.getMod('Coin',self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, 3, CostValue, classMethod, p)
        achieve = {'uid':self.uid,'ValType':0,'Val':1}#成就记录
        if pay < 0:
            Gcore.error(optId, -14002995) #支付失败
        else:
            if not self.mod.doBuyMap(x,y):
                return Gcore.error(optId,-14002004) #购买失败
            else:
                return Gcore.out(optId,achieve=achieve)
Example #38
0
 def insertGifts(self, activityId, awardId):
     '''
                  添加通用礼包记录
     @param activityId:活动Id,1首冲2签到3成长4活跃5鸿运6在线
     @param awardId:奖励Id,各个活动的奖励配置表的Id
     @param TimeStamp:获奖时间
     '''
     day = self.getDeadline(activityId)
     if day == 0:
         perm = 1
     else:
         perm = 0
     row = {
         'UserId': self.uid,
         'ActivityId': activityId,
         'AwardId': awardId,
         'isGet': 0,
         'CreateTime': time.time(),
         'LimiteTime': day,
         'Perm': perm
     }
     table = 'tb_activity_gift'
     res = self.db.insert(table, row)
     #by qiudx 属于通用礼包的将推送给前端
     if res:
         activitys = Gcore.getCfg('tb_cfg_act').values()
         actIdList = [
             activity['ActivityId'] for activity in activitys
             if activity['GeneralShow'] == 1
         ]
         #print actIdList
         if activityId in actIdList:
             num = self.pushGiftNum()
             Gcore.push(109, self.uid, {'GiftNum': num})
     return res
Example #39
0
 def GetSignInLog(self, param={}):
     '''获取签到日志'''
     optId = 23006
     data = self.mod.getSigninLog()
     a = list(data['SignInDate'])
     data['SignInDate'] = ','.join(a)
     #获取全勤奖励信息
     awards = Gcore.getCfg('tb_cfg_act_signin_award').values()
     fullWorkAwards = filter(
         lambda dic: dic['AwardId'] >= 3000 and dic['AwardId'] < 4000,
         awards)
     now = datetime.datetime.now()
     data['FullWorkAwardId'] = fullWorkAwards[now.month - 1]['AwardId']
     #获取周期奖励信息
     finalAwards = Gcore.loadCfg(CFG_ACT_SIGNIN)['FinalAwardId']
     #awards = finalAwards.split(',')
     awards = finalAwards
     signCount = data['SignInCount']
     n = signCount / 30 % len(awards)
     if signCount % 30 == 0:
         n -= 1
     awardId = int(awards[n])
     data['FinalAwardId'] = awardId
     signCount = signCount % 30
     data[
         'SignInDays'] = signCount if signCount else 30  #用于前台显示当前周期内的天数,30天一周期
     data['Refill'] = 5 - data['Refill']
     return Gcore.out(optId, data)
Example #40
0
    def GetPatchNum(self, para={}):
        '''获取碎片的数量'''
        optId = 15132

        #获得碎片的数量
        patchs_num = self.mod.getPatchNum()
        #获得各种武将卡的数量
        cards_num = self.mod.getGeneralCardNum()  #是个字典

        #武将卡的所有类型
        item_ids = Gcore.getCfg('tb_cfg_general_patch').keys()

        #组合成返回结果
        rels = []
        for item_id in item_ids:
            item = {
                'ItemId': item_id,
                'Number': cards_num.get(item_id, 0),
                'Patch1': 0,
                'Patch2': 0,
                'Patch3': 0,
                'Patch4': 0,
            }
            for patch_num in patchs_num:
                if patch_num['ItemId'] == item_id:
                    item.update(patch_num)
                    break
            #if item['Number'] or item['Patch1'] or item['Patch2'] or \
            #    item['Patch3'] or item['Patch4']:
            rels.append(copy.deepcopy(item))

        return Gcore.out(optId, rels)
Example #41
0
 def getClubInfo(self,ClubId=None,fields='*'):
     '''获取军团信息'''
     if ClubId is None:
         return None
     ClubInfo = self.db.out_fields('tb_club',fields, "ClubId = '%s'"%ClubId)
     
     #如果军团信息中包含当前经验,当前等级累积经验,就计算下当前等级剩余经验,升级经验by zhanggh
     for fie in ['ClubTotalExp','ClubLevelTotalExp','ClubLevel']:
         if fie not in ClubInfo:
             return ClubInfo
     
     #by Lizr
     #当前等级剩余经验
     ClubInfo['ClubCurrentExp'] = ClubInfo['ClubTotalExp'] - ClubInfo['ClubLevelTotalExp'] 
     #当前等级升级经验
     cCfgs = Gcore.getCfg('tb_cfg_club_up')
     maxLevel = max(cCfgs.keys())
     clubLevel = ClubInfo['ClubLevel']
     if clubLevel<maxLevel:
         ClubInfo['ClubCurrentExp'] = ClubInfo['ClubTotalExp'] - ClubInfo['ClubLevelTotalExp']
         ClubInfo['ClubUpLevelExp'] = cCfgs[clubLevel+1]['LevelupExp']
     else:
         ClubInfo['ClubCurrentExp'] = cCfgs[maxLevel]['LevelupExp']
         ClubInfo['ClubUpLevelExp'] = cCfgs[maxLevel]['LevelupExp']
     return ClubInfo
Example #42
0
def _test():
    '''测试方法'''
    uid = 1012
    c = Building_altarMod(uid)
    now=time.time()
    c.getMyBuildingType()
    #天坛测试
    skyAltar=Gcore.getCfg('tb_cfg_altar_sky')
    for e in skyAltar.values():
        for s in e:
            print c.distLottery(1, s, now, 10554, 'distLottery')
    #地坛测试
    lankAltar=Gcore.getCfg('tb_cfg_altar_land')
    for e in lankAltar.values():
        for s in e:
            print c.distLottery(2, s, now, 10554, 'distLottery')
Example #43
0
    def getActPoint(self):
        '''获得 剩余行动点数/最大行动点数'''
        BuyActPoint = self.getUserInfo('BuyActPoint')
        row = self._lastActRecord()
        MaxPoint = Gcore.getCfg('tb_cfg_action_point', self.getUserLevel(),
                                'ActPoint')
        if not row:
            RestPoint = MaxPoint + BuyActPoint
        else:
            nowtime = Gcore.common.nowtime()
            PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime', 1200)
            if Gcore.TEST and self.uid in [1001, 43953]:
                PerIncrTime = testPerIncrTime
            if row['ActPoint'] >= MaxPoint:  #已满,不恢复
                RestPoint = row['ActPoint']
            else:
                AccuTime = row['AccuTime'] + (nowtime - row['LastWarTime'])
                incrTimes = AccuTime // PerIncrTime  #回复一点需要多长时间 20分钟
                #print 'incrTimes',incrTimes
                print 'getActPoint.上次剩余', row['ActPoint']
                print 'getActPoint.至已经恢复了', incrTimes
                ActPoint = row['ActPoint'] + incrTimes
                if ActPoint > MaxPoint:
                    ActPoint = MaxPoint
                    print 'getActPoint.剩余+累计越出上限,设为上限', ActPoint

                #查看的时候 不更新累计时间 tb_war_action.AccuTime
                RestPoint = ActPoint

        #print '剩余次数    最大次数',RestPoint,MaxPoint, 前台显示的是: 剩余次数/最大次数
        return (RestPoint, MaxPoint)
Example #44
0
    def Exchange(self, para={}):
        '''货币兑换  by Lizr'''
        optId = 20001
        CoinType =  para['CoinType']
        CoinValue = para['CoinValue']
        if CoinType not in (2, 3):
            return Gcore.error(optId, -20001998) #非法操作
        if type(CoinValue) not in (int, long) or CoinValue <= 0:
            return Gcore.error(optId, -20001998) #非法操作
        
        storageSpace = Gcore.getMod('Building', self.uid).cacStorageSpace(CoinType)
        addPercent = CoinValue / storageSpace
        rateInfos = Gcore.getCfg('tb_cfg_shop_res_sale')
        rateInfoList = filter(lambda dic:dic['AddPercent'] <= addPercent and dic['CoinType'] == CoinType, rateInfos.values())
        rateInfo = max(rateInfoList, key=lambda sale:sale['AddPercent'])

        rate = rateInfo['kPrice1'] * (storageSpace ** rateInfo['kPrice2'])
        GoldValue = int(math.ceil(CoinValue * rate))
#         rate = Gcore.loadCfg(2001).get('exchange').get(str(CoinType))
#         GoldValue = math.ceil(CoinValue/rate)
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, 1, GoldValue, classMethod, para)
        if pay < 0:
            return Gcore.error(optId, -20001995) #支付失败
        else:
            #GainValue = GoldValue*rate
            #GainValue = int(math.ceil(GoldValue / rate))
            #result = modCoin.GainCoin(optId, CoinType, GainValue, classMethod, para)
            result = modCoin.GainCoin(optId, CoinType, CoinValue, classMethod, para)
            body = {"CoinType": CoinType, "CoinValue": CoinValue, "GoldUsed": pay}
            return Gcore.out(optId, body)    
Example #45
0
 def useActPoint(self,point=1):
     '''战役成功,使用一点行动力'''
     BuyActPoint = self.getUserInfo('BuyActPoint')
     if BuyActPoint: 
         if  BuyActPoint>=point:
             cutPoint = point 
             BuyActPoint -= point
         else: #剩余购买行动力已不够扣减
             cutPoint = BuyActPoint
             #point -= BuyActPoint #剩余部分需在未购买处扣
             BuyActPoint =0
             print '剩余购买行动力已不够扣减,point:',point
         sql = 'UPDATE tb_user SET BuyActPoint=BuyActPoint-%s WHERE UserId=%s'%(cutPoint,self.uid)
         self.db.execute(sql)
         #print '已购买的行动力扣1,剩余',BuyActPoint
 
     MaxPoint = Gcore.getCfg('tb_cfg_action_point',self.getUserLevel(),'ActPoint')
     row = self.recoverActPoint(point,0)
     if row: #今天有打过
         pass
     else: #今天未打过
         #print '今天未打过'
         row = {}
         row['ActPoint'] = MaxPoint + BuyActPoint 
         row['LastWarTime'] = Gcore.common.nowtime()
         res = self.db.update('tb_war_action',row,'UserId=%s'%self.uid)
         if not res: #从来没有记录
             row['UserId'] = self.uid
             self.db.insert('tb_war_action',row)
Example #46
0
def _test():
    '''测试方法'''
    uid = 1012
    c = Building_altarMod(uid)
    now = time.time()
    c.getMyBuildingType()
    #天坛测试
    skyAltar = Gcore.getCfg('tb_cfg_altar_sky')
    for e in skyAltar.values():
        for s in e:
            print c.distLottery(1, s, now, 10554, 'distLottery')
    #地坛测试
    lankAltar = Gcore.getCfg('tb_cfg_altar_land')
    for e in lankAltar.values():
        for s in e:
            print c.distLottery(2, s, now, 10554, 'distLottery')
Example #47
0
    def getTechMaxLevel(self,techCategory,techType,bLevel):
        '''
        :查询科技可研究最大等级
        @param techCategory:
        @param techType:
        '''
#         category = 'soldier' if techCategory==1 else 'inter'
#         field = 'max(%sTechLevel)'%category
#         where = '%sType=%s AND BookLevelNeed<=%s'%(category,techType,bLevel)
#         return self.db.out_field('tb_cfg_tech_%s'%category,field,where)
        
        if techCategory==1 and techType<200:
            cfgTable = 'tb_cfg_tech_soldier'
            tlv = 'SoldierTechLevel'
            blv = 'BookLevelNeed'
            tt = 'SoldierType'
            
        elif techCategory==1 and techType>=200:
            cfgTable = 'tb_cfg_wall_school'
            tlv = 'DefenseLevel'
            blv = 'WallLevelNeed'
            tt = 'DefenseType'
            
        else:
            cfgTable = 'tb_cfg_tech_inter'
            tlv = 'InterTechLevel'
            blv = 'BookLevelNeed'
            tt = 'InterType'
        return max([t[tlv] for t in Gcore.getCfg(cfgTable).values() if bLevel>=t[blv] and t[tt]==techType])
Example #48
0
    def GetPatchNum(self, para={}):
        """获取碎片的数量"""
        optId = 15132

        # 获得碎片的数量
        patchs_num = self.mod.getPatchNum()
        # 获得各种武将卡的数量
        cards_num = self.mod.getGeneralCardNum()  # 是个字典

        # 武将卡的所有类型
        item_ids = Gcore.getCfg("tb_cfg_general_patch").keys()

        # 组合成返回结果
        rels = []
        for item_id in item_ids:
            item = {
                "ItemId": item_id,
                "Number": cards_num.get(item_id, 0),
                "Patch1": 0,
                "Patch2": 0,
                "Patch3": 0,
                "Patch4": 0,
            }
            for patch_num in patchs_num:
                if patch_num["ItemId"] == item_id:
                    item.update(patch_num)
                    break
            # if item['Number'] or item['Patch1'] or item['Patch2'] or \
            #    item['Patch3'] or item['Patch4']:
            rels.append(copy.deepcopy(item))

        return Gcore.out(optId, rels)
Example #49
0
    def countGoodsNum(self, goodsIds):
        '''获取道具的数量'''
        # author:zhoujingjiang
        # goodsIds - 道具ID 或 道具ID的序列
        # 返回值:如果goodIds是单个道具,返回该道具的数量;否则返回字典。
        item_ids = Gcore.getCfg('tb_cfg_item').keys()

        is_single = False
        if isinstance(goodsIds, (int, long, basestring)):
            is_single = int(goodsIds)
            goodsIds = [goodsIds]

        for goodsId in iter(goodsIds):
            if int(goodsId) not in item_ids:
                raise TypeError('%s is not an item' % goodsId)

        table = self.tb_bag()
        where = 'UserId=%s AND (GoodsId= ' % self.uid
        where += ' OR GoodsId= '.join(map(str, iter(goodsIds))) + ' ) '
        fields = ['GoodsNum', 'GoodsId']
        items = self.db.out_rows(table, fields, where)

        combined = {}
        for item in items:
            combined[item['GoodsId']] = combined.get(item['GoodsId'], 0) \
                        + item['GoodsNum']
        for goodsId in iter(goodsIds):
            combined.setdefault(int(goodsId), 0)

        return combined if not is_single else combined[is_single]
Example #50
0
    def gainRankReward(self, optId=0):
        '''领取排名奖励'''
        row = self.db.out_fields('tb_rank_fight_last', 'RankId,Rewarded',
                                 'UserId=%s' % self.uid)
        MyRewardRankId = row['RankId']
        Rewarded = row['Rewarded']
        gainRewardList = []
        if Rewarded:
            return gainRewardList

        cfg_rank_reward = Gcore.getCfg('tb_cfg_rank_reward')
        affected = self.db.update('tb_rank_fight_last', {'Rewarded': 1},
                                  'Rewarded=0 AND UserId=%s' % self.uid)
        if affected:
            for k, v in cfg_rank_reward.iteritems():
                if v['RankFrom'] <= MyRewardRankId and MyRewardRankId <= v[
                        'RankTo']:
                    for i in xrange(1, 6):
                        field1 = 'RewardType%s' % i
                        field2 = 'GoodsId%s' % i
                        field3 = 'GoodsNum%s' % i
                        if v[field1] and v[field2]:
                            Gcore.getMod('Reward', self.uid).reward(
                                optId, {}, v[field1], v[field2], v[field3])
                            gainRewardList.append({
                                'RewardType': v[field1],
                                'GoodsId': v[field2],
                                'GoodsNum': v[field3]
                            })
                    break

        return gainRewardList
Example #51
0
    def BuyItemEquip(self, param={}):
        '''商城购买装备或道具'''
        optId = 20006
        
        ieSaleId = param['IeSaleId']
        ieSaleCfg = Gcore.getCfg('tb_cfg_shop_ie_sale', ieSaleId)
        if ieSaleCfg is None:
            return Gcore.error(optId, -20006001)#商品不存在
        modCoin = Gcore.getMod('Coin', self.uid)
        modBag = Gcore.getMod('Bag', self.uid)
        if not modBag.inclueOrNot(ieSaleCfg['SaleType'], ieSaleCfg['GoodsId'], ieSaleCfg['OnceNum']):
            return Gcore.error(optId, -20006002)#背包空间不足
        
        classMethod = '%s,%s'%(self.__class__.__name__,sys._getframe().f_code.co_name)
        res = modCoin.PayCoin(optId, 1, ieSaleCfg['Price'], classMethod, param)

        if res == -2:
            return Gcore.error(optId, -20006994)#货币不足
        if res < 0:
            return Gcore.error(optId, -20006995)#支付失败或者非法操作

        modBag = Gcore.getMod('Bag', self.uid)
        buyId = modBag.addGoods(ieSaleCfg['SaleType'], ieSaleCfg['GoodsId'], ieSaleCfg['OnceNum'], addLog=optId)
        
        recordData = {'uid': self.uid, 'ValType': ieSaleCfg['GoodsId'], 'Val': ieSaleCfg['OnceNum'], 'GoodsType': ieSaleCfg['SaleType']}#成就、任务记录 
        return Gcore.out(optId, {'Result': buyId}, mission = recordData)
Example #52
0
    def inclueOrNot(self, goodsType, goodsId, goodsNum=1):
        '''
        :判断背包是否有足够空间存放物品
        @param goodsType:物品类型 1.装备,2道具 4兵书5宝物
        @param goodsId:装备道具类型
        @param goodsNum:存放数量
        '''
        bagTable = self.tb_bag()
        maxNum = self.getBagSize()  #查询背包容量
        goods = self.db.out_rows(bagTable, ['*'], 'UserId=%s' % self.uid)
        avlBag = self._getAvlInBag(goods, maxNum)  #查询可用的格仔
        if goodsType in (1, 4, 5):
            avlNum = len(avlBag)

        elif goodsType == 2:  #物品类型是否为道具
            overlayNum = Gcore.getCfg('tb_cfg_item', goodsId,
                                      'OverlayNum')  #该类道具最大容量
            avlNum = len(avlBag) * overlayNum
            for good in goods:
                if good['GoodsType'] == 2 and good['GoodsId'] == goodsId:
                    avlNum += (overlayNum - good['GoodsNum'])

        if avlNum >= goodsNum:
            return True
        else:
            return False
Example #53
0
    def achieveTrigger(self,optId,data={'ValType':0,'Val':0}):
        aCfgs = Gcore.getCfg('tb_cfg_achieve')
        activeAction = self._getAchieveCache(optId)
        #查询与OptId对应的成就类型
        aData = {}
        ats = []
        for k in aCfgs.keys():
            optIds = aCfgs[k][1]['OptId'].strip().split(',')
            if (str(optId) in optIds) and (k in activeAction):
                ats.append(k)

        for at in ats:
            
            achieve = self.getAchieveInfo(at)
            aCfg = aCfgs.get(at)
            curAchieve = achieve.get('CurrentAchieve')
            maxAchieve = aCfg[max(aCfg.keys())]['AchieveRequire']
            #成就没完成
            if achieve.get('Finished')==0 and curAchieve<maxAchieve:
                updateVal = self.checkUpdateValue(at,data,curAchieve)
                if updateVal:
                    data = {'CurrentAchieve':updateVal,'NextAchieveId':achieve.get('NextAchieveId')}
                    aData[at] = data
        
        #更新任务
        if aData:
            self.updateAchieve(aData)
Example #54
0
 def inclueOrNot(self,goodsType,goodsId,goodsNum=1):
     '''
     :判断背包是否有足够空间存放物品
     @param goodsType:物品类型 1.装备,2道具 4兵书5宝物
     @param goodsId:装备道具类型
     @param goodsNum:存放数量
     '''
     bagTable = self.tb_bag()
     maxNum = self.getBagSize()#查询背包容量
     goods = self.db.out_rows(bagTable,['*'],'UserId=%s'%self.uid)
     avlBag = self._getAvlInBag(goods, maxNum)#查询可用的格仔
     if goodsType in (1,4,5):
         avlNum = len(avlBag)
         
     elif goodsType==2:#物品类型是否为道具
         overlayNum=Gcore.getCfg('tb_cfg_item',goodsId,'OverlayNum')#该类道具最大容量
         avlNum = len(avlBag)*overlayNum
         for good in goods:
             if good['GoodsType']==2 and good['GoodsId']==goodsId:
                 avlNum+=(overlayNum-good['GoodsNum'])
             
     if avlNum>=goodsNum:
         return True
     else:
         return False   
Example #55
0
 def vipAddTotal(self, optId, goldNum):
     '''
     :玩家充值黄金,增加玩家累积黄金,更新Vip等级
     @param goldNum:增加的黄金数量
     '''
     userInfo = self.getUserInfo(['VipLevel','VipTotalPay'])
     curLevel = userInfo.get('VipLevel')
     curVipTotal = userInfo.get('VipTotalPay')
     
     totalPay = goldNum+curVipTotal
     levelCfg = Gcore.getCfg('tb_cfg_vip_up')
     levelUp = max([levelCfg[level]['VipLevel'] for level in levelCfg if totalPay>=levelCfg[level]['TotalPay']])
     data = {'VipTotalPay':totalPay,'VipLevel':levelUp}
     self.db.update('tb_user',data,'UserId=%s'%self.uid)
     if levelUp>curLevel:#VIP升级
         interMod = Gcore.getMod('Inter',self.uid)
         interMod.updateInterVip()#更新VIP内政加成
         Gcore.setUserData(self.uid,{'VipLevel':levelUp}) #更新用户缓存  Lizr
         Gcore.push(107,self.uid,{'VipLevel':levelUp}) #推送给前端升级 Lizr
     if curVipTotal==0:
         #增加首冲奖励
         Gcore.getMod('Activity',self.uid).insertGifts(1,0)
     #发送系统邮件
     mailMod = Gcore.getMod('Mail', self.uid)
     mailMod.sendSystemMail(self.uid, [], optId, other=[goldNum,])
     
     return levelUp
Example #56
0
    def getTechMaxLevel(self, techCategory, techType, bLevel):
        """
        :查询科技可研究最大等级
        @param techCategory:
        @param techType:
        """
        #         category = 'soldier' if techCategory==1 else 'inter'
        #         field = 'max(%sTechLevel)'%category
        #         where = '%sType=%s AND BookLevelNeed<=%s'%(category,techType,bLevel)
        #         return self.db.out_field('tb_cfg_tech_%s'%category,field,where)

        if techCategory == 1 and techType < 200:
            cfgTable = "tb_cfg_tech_soldier"
            tlv = "SoldierTechLevel"
            blv = "BookLevelNeed"
            tt = "SoldierType"

        elif techCategory == 1 and techType >= 200:
            cfgTable = "tb_cfg_wall_school"
            tlv = "DefenseLevel"
            blv = "WallLevelNeed"
            tt = "DefenseType"

        else:
            cfgTable = "tb_cfg_tech_inter"
            tlv = "InterTechLevel"
            blv = "BookLevelNeed"
            tt = "InterType"
        return max([t[tlv] for t in Gcore.getCfg(cfgTable).values() if bLevel >= t[blv] and t[tt] == techType])