Example #1
0
 def RepairWallDefense(self, p={}):
     '''修复防御工事'''
     optId = 92011
     coinType = 2
     coinValue = self.mod.getRepaireCoin()
     print 'coinValue', coinValue
     if coinValue > 0:
         coinMod = Gcore.getMod('Coin', self.uid)
         payState = coinMod.PayCoin(optId, coinType, coinValue,
                                    'WallUI.RepairWallDefense', p)
         if payState:
             repairNum = self.mod.repairWallDefense()
             if repairNum:  #修复了多少个
                 recordData = {
                     'uid': self.uid,
                     'ValType': 0,
                     'Val': repairNum
                 }
                 return Gcore.out(optId, {
                     'coinType': coinType,
                     'coinValue': coinValue,
                     'repairNum': repairNum
                 },
                                  mission=recordData)
             else:
                 return Gcore.error(optId, -92011997)  #系统失败
         else:
             return Gcore.error(optId, -92011995)  #支付失败
     else:
         return Gcore.error(optId, -92011001)  #无可修复防御工事
Example #2
0
    def StripEquip(self, param={}):
        '''点将台:将武将某个部位的装备脱下来'''
        optId = 15016

        GeneralId = param['GeneralId']
        EquipPart = param['EquipPart']
        Flag = param.get('Flag')  #False脱装备;1脱宝物;其他脱兵书

        modGeneral = Gcore.getMod('General', self.uid)
        General = modGeneral.getGeneralInfo(GeneralId)
        if not General:
            return Gcore.error(optId, -15016001)  #玩家无此武将

        if not Flag:
            stat = modGeneral.stripEquip(General, EquipPart)
            if stat == -1:
                return Gcore.error(optId, -15016002)  #装备部位不正确或该武将在该部位上没有装备
            if stat == -2:
                return Gcore.error(optId, -15016003)  #向背包中增加装备失败
        else:
            stat = modGeneral.stripEquip_EX(GeneralId, Flag)
            if stat == -1:
                return Gcore.error(optId, -15016004)  #没穿兵书或宝物
            if stat == -2:
                return Gcore.error(optId, -15016005)  #背包已满

        #返回
        return Gcore.out(optId, body={})
Example #3
0
    def GetSpawnNum(self, param={}):
        '''获取当前时刻,兵营或工坊的新兵数量'''
        optId = 15030

        BuildingId = param['BuildingId']
        TimeStamp = param['ClientTime']

        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId,
                                                   TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15030001)  #玩家没有该建筑
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15030002)  #建筑正在建造
        if BuildingInfo['BuildingType'] not in (6, 8):
            return Gcore.error(optId, -15030003)  #建筑不是兵营或工坊

        print '建筑ID', BuildingId
        print '建筑类型', BuildingInfo['BuildingType']
        print '建筑等级', BuildingInfo['BuildingLevel']

        modCamp = Gcore.getMod('Building_camp', self.uid)
        spawn_detail = modCamp.getSoldierStorage(BuildingInfo, TimeStamp)
        body = {}
        body['StorageNum'] = spawn_detail['StorageNum']
        body['LastChangedTime'] = spawn_detail['LastChangedTime']

        return Gcore.out(optId, body=body)
Example #4
0
    def SaveTrain(self, param={}):
        '''点将台:保留培养的属性'''
        optId = 15011

        GeneralId = param["GeneralId"]

        modTrain = Gcore.getMod('Building_train', self.uid)
        TrainInfo = modTrain.getTrainRandoms(GeneralId)
        if not TrainInfo:
            return Gcore.error(optId, -15011001)  #没有该武将的培养信息

        #培养所得的属性值
        TrainForce = TrainInfo["RandomForce"]
        TrainWit = TrainInfo["RandomWit"]
        TrainSpeed = TrainInfo["RandomSpeed"]
        TrainLeader = TrainInfo["RandomLeader"]

        modTrain.cancTrainRandoms()  #先将培养信息置为无效

        #更新武将表
        if TrainForce or TrainWit or TrainSpeed or TrainLeader:
            #如果全是0,直接返回。
            stat = modTrain.saveTrainGeneral(GeneralId, TrainForce, TrainWit,
                                             TrainSpeed, TrainLeader)
            if not stat:
                return Gcore.error(optId, -15011002)  #用户没有该武将

        return Gcore.out(optId, {})
Example #5
0
    def checkOpt(self,ckey,optId,optKey,para):

        if optId == 888888:
            result = Gcore.reload()
            print 'Gcore.reload()'
            msg = '<font color=green>Reload Success!</font>' if result is True else "<font color=red>"+str(result)+"</font>"
            response = Gcore.out(optId,{'Result':msg})
            self.Send(ckey,response)
        elif 10001<=optId<=10005: #帐户相关: 10001登录,10002创建帐号,10003随机姓名,10004推荐阵营,10005检查帐户名是否合法
            self.checkLogin(ckey,optId,optKey,para)
        else:
            if optId == 8888: #测试
                #print 'Gcore.getDB(uid)>',Gcore.getDB(uid)
                self.mqPush(ckey,optId,optKey,para)
            else:
                uid = self.Clients[ckey]['uid']
                if uid==0:
                    response = Gcore.error(optId,-88888888) 
                    self.Send(ckey,response) 
                    print 'Please login first'
                    return
                response = proManager.checkOpt(uid, optId, para)
                if type(response) is not dict:
                    #print 'type(response)',type(response),response
                    response = Gcore.error(optId,-33333333) #协议号未定义 或返回出错
                    
                response['opt_key'] = optKey
                self.Send(ckey,response)
Example #6
0
    def SaveTrain(self, param = {}):
        '''点将台:保留培养的属性'''
        optId = 15011
        
        GeneralId = param["GeneralId"]

        modTrain = Gcore.getMod('Building_train', self.uid)
        TrainInfo = modTrain.getTrainRandoms(GeneralId)
        if not TrainInfo:
            return Gcore.error(optId, -15011001) #没有该武将的培养信息
        
        #培养所得的属性值
        TrainForce = TrainInfo["RandomForce"]
        TrainWit = TrainInfo["RandomWit"]
        TrainSpeed = TrainInfo["RandomSpeed"]
        TrainLeader = TrainInfo["RandomLeader"]
        
        modTrain.cancTrainRandoms() #先将培养信息置为无效
        
        #更新武将表
        if TrainForce or TrainWit or TrainSpeed or TrainLeader:
            #如果全是0,直接返回。
            stat = modTrain.saveTrainGeneral(GeneralId, TrainForce, TrainWit, 
                                             TrainSpeed, TrainLeader)        
            if not stat:
                return Gcore.error(optId, -15011002) #用户没有该武将

        return Gcore.out(optId, {})
Example #7
0
    def BuyActPoint(self, para={}):
        '''购买行动点数'''
        optId = 91004
        MaxBuyActTimes = Gcore.loadCfg(9101).get('MaxBuyActTimes')
        TodayBuyTimes = self.mod.getTodayBuyTimes()
        print 'TodayBuyTimes', TodayBuyTimes
        if MaxBuyActTimes <= TodayBuyTimes:
            Gcore.out(optId, -91004001)  #已达可购买上限
        else:
            TodayBuyTimes += 1
            CostValue = Gcore.loadCfg(9101).get('BuyTimesPrice').get(
                str(TodayBuyTimes))
            if CostValue is None:
                CostValue = max(
                    Gcore.loadCfg(9101).get('BuyTimesPrice').values())
            #开始支付
            modCoin = Gcore.getMod('Coin', self.uid)
            pay = modCoin.PayCoin(optId, 1, CostValue, 'WarUI.BuyActTimes',
                                  para)
            if pay < 0:
                return Gcore.error(optId, -91004995)  #支付失败
            else:
                result = self.mod.buyActPoint()
                if not result:
                    return Gcore.error(optId, -91004002)  #系统错误

        body = {}
        body['CanBuy'] = 1 if TodayBuyTimes < MaxBuyActTimes else 0
        RestPoint, MaxPoint = self.mod.getActPoint()
        body['RestPoint'] = RestPoint
        body['MaxPoint'] = MaxPoint
        return Gcore.out(optId, body)
Example #8
0
 def BuyActPoint(self,para={}):
     '''购买行动点数'''
     optId = 91004
     MaxBuyActTimes = Gcore.loadCfg(9101).get('MaxBuyActTimes')
     TodayBuyTimes = self.mod.getTodayBuyTimes()
     print 'TodayBuyTimes',TodayBuyTimes
     if MaxBuyActTimes <= TodayBuyTimes:
         Gcore.out(optId, -91004001) #已达可购买上限
     else:
         TodayBuyTimes += 1
         CostValue = Gcore.loadCfg(9101).get('BuyTimesPrice').get( str(TodayBuyTimes) )
         if CostValue is None:
             CostValue = max( Gcore.loadCfg(9101).get('BuyTimesPrice').values() )
         #开始支付
         modCoin = Gcore.getMod('Coin', self.uid)
         pay = modCoin.PayCoin(optId, 1, CostValue, 'WarUI.BuyActTimes', para)
         if pay < 0:
             return Gcore.error(optId, -91004995) #支付失败
         else:            
             result = self.mod.buyActPoint()
             if not result:
                 return Gcore.error(optId, -91004002) #系统错误
     
     body = {}
     body['CanBuy'] = 1 if TodayBuyTimes < MaxBuyActTimes else 0
     RestPoint,MaxPoint = self.mod.getActPoint()
     body['RestPoint'] = RestPoint
     body['MaxPoint'] = MaxPoint
     return Gcore.out(optId, body)
Example #9
0
    def StripEquip(self, param={}):
        '''点将台:将武将某个部位的装备脱下来'''
        optId = 15016
        
        GeneralId = param['GeneralId']
        EquipPart = param['EquipPart']
        Flag = param.get('Flag') #False脱装备;1脱宝物;其他脱兵书
        
        modGeneral = Gcore.getMod('General', self.uid)
        General = modGeneral.getGeneralInfo(GeneralId)
        if not General:
            return Gcore.error(optId, -15016001) #玩家无此武将
        
        if not Flag:
            stat = modGeneral.stripEquip(General, EquipPart)
            if stat == -1:
                return Gcore.error(optId, -15016002) #装备部位不正确或该武将在该部位上没有装备
            if stat == -2:
                return Gcore.error(optId, -15016003) #向背包中增加装备失败
        else:
            stat = modGeneral.stripEquip_EX(GeneralId, Flag)
            if stat == -1:
                return Gcore.error(optId, -15016004) #没穿兵书或宝物
            if stat == -2:
                return Gcore.error(optId, -15016005) #背包已满

        #返回
        return Gcore.out(optId, body={})
Example #10
0
    def GetSpawnNum(self, param={}):
        '''获取当前时刻,兵营或工坊的新兵数量'''
        optId = 15030

        BuildingId = param['BuildingId']
        TimeStamp = param['ClientTime']
        
        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15030001) #玩家没有该建筑
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15030002) #建筑正在建造
        if BuildingInfo['BuildingType'] not in (6, 8):
            return Gcore.error(optId, -15030003) #建筑不是兵营或工坊
        
        print '建筑ID', BuildingId
        print '建筑类型', BuildingInfo['BuildingType']
        print '建筑等级', BuildingInfo['BuildingLevel']

        modCamp = Gcore.getMod('Building_camp', self.uid) 
        spawn_detail= modCamp.getSoldierStorage(BuildingInfo, TimeStamp)
        body = {}
        body['StorageNum'] = spawn_detail['StorageNum']
        body['LastChangedTime'] = spawn_detail['LastChangedTime']

        return Gcore.out(optId, body=body)
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 ApplyClub(self,p={}):
     '''
     :申请加入
     '''
     optId = 15064
     clubId = p['ClubId']
     building = self.mod.getClubBuildingInfo()
     if building is None:
         return  Gcore.error(optId,-15064901)#外史院建筑不存在
     clubInfo = self.mod.getClubInfo(clubId)
     if not clubInfo:
         return Gcore.error(optId,-15064920)#军团不存在
     if self.mod.getUserClubId():
         return Gcore.error(optId,-15064001)#只能加入一个军团
     
     if not self.mod.validApplyInterval():
         return Gcore.error(optId,-15064004)#离上次退出军团时间间隔不合法
     
     memberNum = self.mod.getClubMemberNum(clubId)
     if memberNum.get('CurNum')>=memberNum.get('MaxNum'):
         return Gcore.error(optId,-15064002)#军团成员已满
     allowState = clubInfo.get('AllowState')
     if allowState == 1:#需要审核
         self.mod.applyClub(clubId)
         return Gcore.out(optId,{'Passed':0,'ClubId':clubId})#申请成功,审核中
     elif allowState ==2:#不需审核
         self.mod.applyClub(clubId)
         self.mod.agreeApply(optId, clubId, self.uid)
         Gcore.setUserData(self.uid, {'ClubId':clubId})#更新用户缓存
         
         recordData = {'uid':self.uid,'ValType':0,'Val':1}#任务
         return Gcore.out(optId,{'Passed':1,'ClubId':clubId},mission=recordData)#成功加入军团
     else:
         return Gcore.out(optId,{'Passed':2})#不允许加入
Example #13
0
    def checkOpt(self, ckey, optId, optKey, para):

        if optId == 888888:
            result = Gcore.reload()
            print 'Gcore.reload()'
            msg = '<font color=green>Reload Success!</font>' if result is True else "<font color=red>" + str(
                result) + "</font>"
            response = Gcore.out(optId, {'Result': msg})
            self.Send(ckey, response)
        elif 10001 <= optId <= 10005:  #帐户相关: 10001登录,10002创建帐号,10003随机姓名,10004推荐阵营,10005检查帐户名是否合法
            self.checkLogin(ckey, optId, optKey, para)
        else:
            if optId == 8888:  #测试
                #print 'Gcore.getDB(uid)>',Gcore.getDB(uid)
                self.mqPush(ckey, optId, optKey, para)
            else:
                uid = self.Clients[ckey]['uid']
                if uid == 0:
                    response = Gcore.error(optId, -88888888)
                    self.Send(ckey, response)
                    print 'Please login first'
                    return
                response = proManager.checkOpt(uid, optId, para)
                if type(response) is not dict:
                    #print 'type(response)',type(response),response
                    response = Gcore.error(optId, -33333333)  #协议号未定义 或返回出错

                response['opt_key'] = optKey
                self.Send(ckey, response)
Example #14
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 #15
0
 def SlaveOperand(self, param={}):
     '''对藩国的操作    纳贡 或 释放'''
     optId = 15121
     
     typ = param['typ'] #操作类型:1,纳贡。2,释放。
     uid = param['uid'] #藩国UserId
     sid = param['sid'] #藩国ServerId
     ts = param['ClientTime'] #客户端时间戳
     recordData = {}#成就记录
     
     stat = self.mod.isMyHold(uid, sid)
     if not stat: #不是玩家的藩国
         return Gcore.error(optId, -15121001)  
     Jcoin, Gcoin = stat[0], stat[1]
            
     modCoin = Gcore.getMod('Coin', self.uid)
     classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
     if typ == 1: #1,纳贡
         if Jcoin == 0 and Gcoin == 0:
             return Gcore.error(optId, -15121002) #不可收集
         j = modCoin.GainCoin(optId, 2, Jcoin, classMethod, param)
         g = modCoin.GainCoin(optId, 3, Gcoin, classMethod, param)
         if j < -1 or g < -1:
             return Gcore.error(optId, -15121003) #增加货币操作失败
         j = 0 if Jcoin==0 else j
         g = 0 if Gcoin==0 else g
         self.mod.collect(uid, sid, j, g, ts)
         recordData = {'uid':self.uid,'ValType':0,'Val':1}#成就记录
     elif typ == 2: #2,释放。
         j = modCoin.GainCoin(optId, 2, Jcoin, classMethod, param)
         g = modCoin.GainCoin(optId, 3, Gcoin, classMethod, param)
         self.mod.free(uid, sid, ts)
     else:
         return Gcore.error(optId, -15121005) #操作类型错误
     return Gcore.out(optId, body = {"Jcoin":j, "Gcoin":g},mission=recordData)     
Example #16
0
    def CollectCoin(self, param = {}):
        '''磨坊2,铸币厂5:收集资源'''
        #By Zhanggh 2013-3-20
        optId = 15005
        BuildingId = param.get('BuildingId')
        CollectTimeStamp = param.get('ClientTime')
        StorageReq = param.get('StorageReq')
        
        #验证客户端与服务器的时差

        BuildingInfo = self.buildingMod.getBuildingById(BuildingId)
        if not BuildingInfo:
            return Gcore.error(optId, -15005901) #用户没有该建筑
        BuildingType = BuildingInfo['BuildingType']
        if BuildingType !=2 and BuildingType!=5:
            return Gcore.error(optId, -15005998) #建筑非军需所或铸币厂
        if BuildingInfo.get('BuildingState')==2:
            return Gcore.error(optId, -15005905)#建筑升级中
        
        #收集资源,返回收集资源后剩余的部分与误差
        returnInfo = self.mod.collectCoin(optId,BuildingType,BuildingId,CollectTimeStamp,StorageReq,param)
        if returnInfo==0:
            return Gcore.error(optId, -15005001) #没有可收集资源
        elif returnInfo==-1:
            return Gcore.error(optId, -15005002) #建筑修复中
        
        CoinType = 2 if BuildingType == 2 else 3
        CollectNum = returnInfo.pop('CNum')   
        recordData = {'uid':self.uid,'ValType':CoinType,'Val':CollectNum}#成就记录
            
        return Gcore.out(optId,returnInfo,achieve=recordData,mission=recordData)
Example #17
0
    def CancelBuilding(self, param={}):
        '''通用:取消建筑建造或升级'''
        optId = 15003

        BuildingId = param["BuildingId"]
        TimeStamp = param['ClientTime']

        BuildingInfo = self.mod.getBuildingById(BuildingId, 
                                                ['BuildingPrice', 
                                                 'BuildingType', 
                                                 'CoinType',
                                                 'LastOptType'], 
                                                TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15003003) #用户没有该建筑
        
        #BuildingType < 100 是建筑;大于100是装饰;
        if BuildingInfo['BuildingType'] < 100 and \
        BuildingInfo['BuildingState'] == 0:
            return Gcore.error(optId, -15003004) #建筑已建造或升级完成,不能取消。
        
        BuildingType = BuildingInfo['BuildingType']
        CostValue = BuildingInfo["BuildingPrice"]
        CostType = BuildingInfo["CoinType"]
        
        #返钱
        CancelReturn = Gcore.loadCfg(
            Gcore.defined.CFG_BUILDING)["CancelReturn"] #返还比例
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, 
                                 sys._getframe().f_code.co_name)
        gain = modCoin.GainCoin(optId, CostType, 
                                int(CostValue * CancelReturn), 
                                classMethod, param)
        if gain < 0:
            return Gcore.error(optId, -15003005) #增加货币失败

        #建筑正在建造 :如果是装饰,删掉。
        if BuildingInfo['BuildingType'] > 100 or \
        BuildingInfo['BuildingState'] == 1:
            self.mod.deleteBuildingById(BuildingId)
        else:
            #更新建筑表
            UpInfo = {}
            UpInfo['CompleteTime'] = TimeStamp
            UpInfo['BuildingLevel'] = BuildingInfo['BuildingRealLevel']
            UpInfo['LastOptType'] = 2
            self.mod.updateBuildingById(UpInfo, BuildingId)
        #不同类型的建筑进行不同的操作
        # + todo
        if BuildingType in (6, 7, 8): #校场 兵营 工坊:计算士兵
            modCamp = Gcore.getMod('Building_camp', self.uid)
            modCamp.TouchAllSoldiers(TimeStamp=TimeStamp)
            if BuildingType in (6, 8): #兵营 工坊 回复生产
                update_dic = {'LastChangedTime':TimeStamp, 
                              'BuildingLevel':BuildingInfo['BuildingRealLevel']}
                modCamp.updateProcessById(update_dic, BuildingId)
        return Gcore.out(optId, 
                         {'Coin%s'%CostType:modCoin.getCoinNum(CostType), 
                          "RetValue":int(CostValue * CancelReturn)})
Example #18
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 #19
0
    def SpeedRapidPractise(self, param={}):
        '''加速突飞训练的冷却时间'''
        optId = 15094

        IsSpeed = param.get('IsSpeed')
        TimeStamp = param['ClientTime']

        TodayDate = time.strftime('%Y-%m-%d', time.localtime(TimeStamp))
        modGround = Gcore.getMod('Building_ground', self.uid)
        RapidRecord = modGround.getRapidRecord(TodayDate)

        if not RapidRecord:
            RapidCount = 0
            IsOverFlow = 0

            CDValue = 0
        else:
            RapidCount = RapidRecord['PractiseCount']
            IsOverFlow = RapidRecord['IsOverFlow']

            TotalCD = RapidRecord['CDValue']
            SecondsPast = TimeStamp - RapidRecord['LastRapidTime']
            CDValue = max(TotalCD - SecondsPast, 0)
            if CDValue <= 0:
                IsOverFlow = 0

        if not IsSpeed:  #不是加速
            body = {}
            body['TimeStamp'] = TimeStamp
            body['IsOverFlow'] = IsOverFlow
            body['CDValue'] = CDValue
            body['RapidCout'] = RapidCount
            return Gcore.out(optId, body=body)

        #加速冷却时间
        if CDValue <= 0:
            return Gcore.error(optId, -15094001)  #冷却时间为0

        CoinType = 1
        CoinValue = calSpeedCost(4, CDValue)

        #扣钱
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, CoinType, CoinValue, classMethod, param)
        if pay < 0:
            return Gcore.error(optId, -15094002)  #扣钱失败

        #更新突飞记录表
        modGround.speedCD()

        body = {}
        body['GoldenCost'] = pay
        body['CDValue'] = 0
        body['SpeedTime'] = CDValue
        body['IsOverFlow'] = 0
        body['TimeStamp'] = TimeStamp
        return Gcore.out(optId, body=body)
Example #20
0
    def MoveGeneral(self, param={}):
        '''校杨:移动武将'''
        optId = 15102

        GeneralId = param['GeneralId']
        PosId = param.get('PosId')

        modGeneral = Gcore.getMod('General', self.uid)
        EmbattleInfo = modGeneral.getMyGeneralsOnEmbattle(
            ['GeneralId', 'PosId'])

        OnEmbattle = [
            General['PosId'] for General in EmbattleInfo
            if General['GeneralId'] == GeneralId
        ]
        IsOccupy = [
            General['GeneralId'] for General in EmbattleInfo
            if General['PosId'] == PosId
        ]

        GeneralNum = len(EmbattleInfo)
        recordData = {
            'uid': self.uid,
            'ValType': 0,
            'Val': 1,
            'GNum': 0
        }  #成就、任务记录

        if (not OnEmbattle) and (not PosId):
            return Gcore.error(optId, -15102001)  #武将不在阵上无法移除

        if OnEmbattle and (not PosId):  #从阵上移除武将
            GeneralNum -= 1
            self.mod.deletePos(GeneralId)
            recordData['GNum'] = GeneralNum
            return Gcore.out(optId, body={}, mission=recordData)

        if PosId not in range(1, 10, 1):  #位置是1-9
            return Gcore.error(optId, -15102004)

        if OnEmbattle and IsOccupy:  #互换两名武将的位置
            stat = self.mod.exchangePos(GeneralId, OnEmbattle[0], IsOccupy[0],
                                        PosId)
        if OnEmbattle and (not IsOccupy):
            stat = self.mod.movePos(GeneralId, PosId)
        if (not OnEmbattle) and IsOccupy:
            stat = self.mod.insteadPos(GeneralId, IsOccupy[0], PosId)

        if (not OnEmbattle) and (not IsOccupy):
            #判断阵上武将是否满员
            if len(EmbattleInfo) >= 5:
                return Gcore.error(optId, -15102002)  #阵上武将已满
            GeneralNum += 1
            stat = self.mod.addPos(GeneralId, PosId)
        if not stat:
            return Gcore.error(optId, -15102003)  #布阵操作失败

        recordData['GNum'] = GeneralNum
        return Gcore.out(optId, body={}, mission=recordData)
Example #21
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 #22
0
 def SpeedRapidPractise(self, param={}):
     '''加速突飞训练的冷却时间'''
     optId = 15094
     
     IsSpeed = param.get('IsSpeed')
     TimeStamp = param['ClientTime']
     
     TodayDate = time.strftime('%Y-%m-%d', time.localtime(TimeStamp))
     modGround = Gcore.getMod('Building_ground', self.uid)
     RapidRecord = modGround.getRapidRecord(TodayDate)
     
     if not RapidRecord:
         RapidCount = 0
         IsOverFlow = 0
         
         CDValue = 0
     else:
         RapidCount = RapidRecord['PractiseCount']
         IsOverFlow = RapidRecord['IsOverFlow']
         
         TotalCD = RapidRecord['CDValue']
         SecondsPast = TimeStamp - RapidRecord['LastRapidTime']
         CDValue = max(TotalCD - SecondsPast, 0)
         if CDValue <= 0:
             IsOverFlow = 0
     
     if not IsSpeed: #不是加速
         body = {}
         body['TimeStamp'] = TimeStamp
         body['IsOverFlow'] = IsOverFlow
         body['CDValue'] = CDValue
         body['RapidCout'] = RapidCount
         return Gcore.out(optId, body=body)
     
     #加速冷却时间
     if CDValue <= 0:
         return Gcore.error(optId, -15094001) #冷却时间为0
     
     CoinType = 1
     CoinValue = calSpeedCost(4, CDValue)
     
     #扣钱
     modCoin = Gcore.getMod('Coin', self.uid)
     classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
     pay = modCoin.PayCoin(optId, CoinType, CoinValue, classMethod, param)
     if pay < 0:
         return Gcore.error(optId, -15094002) #扣钱失败
     
     #更新突飞记录表
     modGround.speedCD()
     
     body = {}
     body['GoldenCost'] = pay
     body['CDValue'] = 0
     body['SpeedTime'] = CDValue
     body['IsOverFlow'] = 0
     body['TimeStamp'] = TimeStamp
     return Gcore.out(optId, body=body)
Example #23
0
    def CancelBuilding(self, param={}):
        '''通用:取消建筑建造或升级'''
        optId = 15003

        BuildingId = param["BuildingId"]
        TimeStamp = param['ClientTime']

        BuildingInfo = self.mod.getBuildingById(BuildingId, 
                                                ['BuildingPrice', 
                                                 'BuildingType', 
                                                 'CoinType',
                                                 'LastOptType'], 
                                                TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15003003) #用户没有该建筑
        
        #BuildingType < 100 是建筑;大于100是装饰;
        if BuildingInfo['BuildingType'] < 100 and \
        BuildingInfo['BuildingState'] == 0:
            return Gcore.error(optId, -15003004) #建筑已建造或升级完成,不能取消。
        
        BuildingType = BuildingInfo['BuildingType']
        CostValue = BuildingInfo["BuildingPrice"]
        CostType = BuildingInfo["CoinType"]
        
        #返钱
        CancelReturn = Gcore.loadCfg(
            Gcore.defined.CFG_BUILDING)["CancelReturn"] #返还比例
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, 
                                 sys._getframe().f_code.co_name)
        gain = modCoin.GainCoin(optId, CostType, 
                                int(CostValue * CancelReturn), 
                                classMethod, param)
        if gain < 0:
            return Gcore.error(optId, -15003005) #增加货币失败

        #建筑正在建造 :如果是装饰,删掉。
        if BuildingInfo['BuildingType'] > 100 or \
        BuildingInfo['BuildingState'] == 1:
            self.mod.deleteBuildingById(BuildingId)
        else:
            #更新建筑表
            UpInfo = {}
            UpInfo['CompleteTime'] = TimeStamp
            UpInfo['BuildingLevel'] = BuildingInfo['BuildingRealLevel']
            UpInfo['LastOptType'] = 2
            self.mod.updateBuildingById(UpInfo, BuildingId)
        #不同类型的建筑进行不同的操作
        # + todo
        if BuildingType in (6, 8): #校场 兵营 工坊:计算士兵
            modCamp = Gcore.getMod('Building_camp', self.uid)
            modCamp.updateStorage(BuildingId, last_changed_time=TimeStamp, last_cal_time=TimeStamp)
        return Gcore.out(optId, 
                         {'Coin%s'%CostType:modCoin.getCoinNum(CostType), 
                          "RetValue":int(CostValue * CancelReturn)})
Example #24
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 #25
0
    def GetGift(self, param={}):
        '''领取通用礼包奖励'''
        optId = 23003
        giftId = param['GiftId']

        row = {"isGet": 1}
        where = "GiftId=%s AND UserId=%s AND isGet=0" % (giftId, self.uid)
        affectedrows = self.mod.db.update('tb_activity_gift', row, where)
        if not affectedrows:
            return Gcore.error(optId, -23003002)  #礼包已经领取

        giftInfo = self.mod.getGiftInfo(giftId)
        if not giftInfo:
            return Gcore.error(optId, -23003001)  #礼包领取条件不符
        elif not giftInfo.get('Valid', 0):
            return Gcore.error(optId, -23003003)  #礼包已过期

        activityId = giftInfo['ActivityId']
        awardId = giftInfo['AwardId']
        if activityId == 2:
            table = 'tb_cfg_act_signin_award'
        elif activityId == 3:
            table = 'tb_cfg_act_grow_award'
        elif activityId == 4:
            table = 'tb_cfg_act_active_award'
        else:
            return Gcore.error(optId, -23003999)

        award = Gcore.getCfg(table, awardId)
        modReward = Gcore.getMod('Reward', self.uid)
        gain = []
        emailed = 0
        for i in xrange(1, 4):
            g = {}
            g['ActivityId'] = activityId
            g['AwardType'] = award['AwardType%s' % i]
            g['GoodsId'] = award['GoodsId%s' % i]
            g['Gain'] = modReward.reward(optId, param,
                                         award['AwardType%s' % i],
                                         award['GoodsId%s' % i],
                                         award['GoodsNum%s' % i])
            if award['AwardType%s' % i] == 1 and (g['Gain'] == 0 or len(
                    g['Gain']) != award['GoodsNum%s' % i]):
                emailed = 1
            elif award['AwardType%s' % i] == 2 and (
                    g['Gain'] == 0 or g['Gain'][0] != award['GoodsNum%s' % i]):
                emailed = 1
            if award['AwardType%s' % i] != 3 and g['Gain'] != 0:
                g['Gain'] = g['Gain'][0]
            gain.append(g)
        #self.mod.updateGifts(activityId, awardId)
        return Gcore.out(optId, {
            'Awards': gain,
            'GiftId': giftId,
            'Emailed': emailed
        })
Example #26
0
    def FullAddSoldier(self, param={}):
        '''填满兵营或工坊的剩余训练空间'''
        optId = 15031

        BuildingId = param['BuildingId']
        TimeStamp = param['ClientTime']

        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId,
                                                   TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15031001)  #玩家没有该建筑
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15031002)  #建筑正在建造
        if BuildingInfo['BuildingType'] not in (6, 8):
            return Gcore.error(optId, -15031003)  #建筑不是兵营或工坊

        modCamp = Gcore.getMod('Building_camp', self.uid)
        spawn_detail = modCamp.getSoldierStorage(BuildingInfo, TimeStamp)

        MaxNum = Gcore.getCfg(
            'tb_cfg_building_up',
            (BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel']),
            'MakeValue')
        buy_cnt = MaxNum - spawn_detail['StorageNum']
        print '兵营或工坊的最大数量', MaxNum
        print '当前时刻的数量', spawn_detail['StorageNum']
        print '购买数量', buy_cnt

        if buy_cnt < 0:
            return Gcore.error(optId, -15031004)  #兵营或工坊已满
        elif buy_cnt > 0:
            coin_need = calSpeedCost(3, buy_cnt)
            class_method = '%s.%s' % (self.__class__.__name__,
                                      sys._getframe().f_code.co_name)
            modCoin = Gcore.getMod('Coin', self.uid)
            pay = modCoin.PayCoin(optId, 1, coin_need, class_method, param)
            if pay < 0:
                return Gcore.error(optId, -15031005)  #支付失败

            #将兵营置满
            modCamp.fullAddSoldier(
                BuildingId, BuildingInfo['BuildingType'],
                BuildingInfo['BuildingRealLevel'],
                max(spawn_detail['LastChangedTime'], TimeStamp), TimeStamp)
        else:
            pay = 0

        body = {}
        body['StorageNum'] = MaxNum
        body['BuyCnt'] = buy_cnt
        body['GoldenCoinCost'] = pay
        body['TimeStamp'] = TimeStamp

        return Gcore.out(optId, body=body)
Example #27
0
    def GetReward(self,p={}):
        '''
                    领取任务奖励
        '''
        optId=22003
        mId=p['MID']
        
        mCfg = Gcore.getCfg('tb_cfg_mission',mId)
        if mCfg is None:
            return Gcore.error(optId,-22003001)#任务不存在
#         mInfo = self.mod.getMissionInfo(mId)
#         if mInfo is None:
#             return Gcore.error(optId,-22003001)#任务不存在
#         #1: 新接,2:进行中,3:已完成,4:已领取奖励
#         elif mInfo.get('Status')!=3:
#             return Gcore.error(optId,-22003002)#任务未完成
        whereClause = 'UserId=%s AND MissionId=%s AND Status=3'%(self.uid,mId)
        updateFlag = self.mod.updateMissionByWhere({'Status':4},whereClause)#先更新任务状态,防止并发
        if not updateFlag:
            return Gcore.error(optId,-22003002)#任务未完成
        #领取奖励
        coinMod = Gcore.getMod('Coin',self.uid)
        playerMod = Gcore.getMod('Player',self.uid)
        rewardMod = Gcore.getMod('Reward',self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
        
        expReward = mCfg.get('RewardExp',0)
        JCReward = mCfg.get('RewardJCoin',0)
        GCReward = mCfg.get('RewardGCoin',0)
        GReward = mCfg.get('RewardGold',0)
        
        #发放奖励
        playerMod.addUserExp(0,expReward,optId)
        coinMod.GainCoin(optId,1,GReward,classMethod,p)
        coinMod.GainCoin(optId,2,JCReward,classMethod,p)
        coinMod.GainCoin(optId,3,GCReward,classMethod,p)
        
        rt1 = mCfg.get('RewardType1',0)
        rt2 = mCfg.get('RewardType2',0)
        equipIds = []
        if rt1!=0:
            f = rewardMod.reward(optId,p,rt1,mCfg['GoodsId1'],mCfg['GoodsNum1'])
            if rt1==1 and isinstance(f,list):
                equipIds = equipIds+f
        if rt2!=0:
            f = rewardMod.reward(optId,p,rt2,mCfg['GoodsId2'],mCfg['GoodsNum2'])
            if rt2==1 and isinstance(f,list):
                equipIds = equipIds+f
#         self.mod.updateMissions({mId:{'Status':4}})
        self.mod.getNewMission(mId)
        
        myMissions =self.mod.getMyMissions()
        myMissions = com.list2dict(myMissions,0)
        re={'EIds':equipIds,'MLS':myMissions}
        return Gcore.out(optId,re)
Example #28
0
    def OpenBox(self, p={}):
        '''开宝箱'''
        optId = 15082
        boxType = p['BoxType']
        boxCfg = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost')
        boxTypes = [int(i) for i in boxCfg.keys()]
        if boxType not in boxTypes:
            return Gcore.error(optId, -15082999)  #参数错误
        building = self.mod.getClubBuildingInfo()
        if building is None:
            return Gcore.error(optId, -15082901)  #外史院建筑不存在
        clubId = self.mod.getUserClubId()
        if not clubId:
            return Gcore.error(optId, -15082920)  #军团不存在

        #支付贡献
        cost = boxCfg.get(str(boxType))
        left = self.mod.payDevote(clubId, cost)
        #         left = 1

        #支付成功,开始抽奖
        if left >= 0:
            goodsCfg = Gcore.getCfg('tb_cfg_club_box', boxType)
            lucky = com.Choice(goodsCfg)
            rType = lucky.get('RewardType')
            goodsId = lucky['GoodsId']
            goodsNum = lucky['GoodsNum']
            body = {
                'Left': left,
                'RewardType': rType,
                'GoodsId': goodsId,
                'GoodsNum': goodsNum
            }
            equipIds = []
            #             if rType in [1,2,3]:#装备,道具,资源
            ids = Gcore.getMod('Reward',
                               self.uid).reward(optId, p, rType, goodsId,
                                                goodsNum)
            if rType == 1:
                if isinstance(ids, list):
                    equipIds = ids

            body['EIDS'] = equipIds
            self.mod.insertBoxLog(clubId, boxType, lucky)

            body['Logs'] = self.mod.getBoxLogList(1,
                                                  clubId,
                                                  offset=0,
                                                  pageSize=2,
                                                  timeLimit=False)
            recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1}  #成就,任务记录

            return Gcore.out(optId, body, mission=recordData)
        else:
            return Gcore.error(optId, -15082002)  # 支付失败
Example #29
0
    def ChangeSoldierNum(self, param={}):
        '''校场:改变武将的带兵类型,数量'''
        optId = 15103

        GeneralId = param['GeneralId']
        SoldierNum = param['SoldierNum']
        SoldierType = param['SoldierType']
        TimeStamp = param['ClientTime']

        modGeneral = Gcore.getMod('General', self.uid)
        Generals = modGeneral.getLatestGeneralInfo(TimeStamp=TimeStamp)
        GeneralsOnEmbattle = [
            General for General in Generals if General["PosId"] != 0
        ]

        GeneralInfo = None
        SoldierOnEmbattle = 0
        for GeneralOnEmbattle in GeneralsOnEmbattle:
            if GeneralOnEmbattle['GeneralId'] == GeneralId:
                GeneralInfo = GeneralOnEmbattle
            if GeneralOnEmbattle['TakeType'] == SoldierType:
                SoldierOnEmbattle += GeneralOnEmbattle['TakeNum']

        kLeader = Gcore.loadCfg(
            Gcore.defined.CFG_BATTLE)["kLeaderAddNum"]  #每统帅带兵数
        if not GeneralInfo:
            return Gcore.error(optId, -15103001)  #该武将没上阵或没有该武将
        if SoldierNum > (GeneralInfo['LeaderValue'] * kLeader):  #需要改成读配置
            return Gcore.error(optId, -15103002)  #带兵数量过大

        #校场的士兵数量
        modCamp = Gcore.getMod('Building_camp', self.uid)
        Soldiers = modCamp.getSoldierNum(TimeStamp)

        #空闲士兵数量
        SoldierFree = Soldiers.get('Soldier%s' % SoldierType,
                                   0) - SoldierOnEmbattle

        #武将带兵数量
        if SoldierNum <= GeneralInfo['TakeNum']:
            TakeNum = SoldierNum
        else:
            TakeNum = min(SoldierNum, GeneralInfo['TakeNum'] + SoldierFree)

        UpGeneralInfo = {"TakeNum": TakeNum, "TakeType": SoldierType}
        modGeneral.updateGeneralById(UpGeneralInfo, GeneralId)

        recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1}  #成就、任务记录
        return Gcore.out(optId,
                         body={
                             "TakeNum": TakeNum,
                             "TakeType": SoldierType
                         },
                         mission=recordData)
Example #30
0
 def GainRankReward(self,para={}):
     '''领取排名奖励'''
     optId = 24003
     checkstate = self.mod.checkGetReward()
     if checkstate == -1:
         return Gcore.error(optId,-24003001) #您今天已经领取过奖励
     if checkstate == -2:
         return Gcore.error(optId,-24003002) #不符合领取奖励条件
     else:
         gainRewardList = self.mod.gainRankReward(optId)
         return Gcore.out(optId,{'gainRewardList':gainRewardList})
Example #31
0
    def InviteGenerals(self, param={}):
        '''招贤馆:招募武将'''
        optId = 15007

        GeneralType = param["GeneralType"]
        InviteTimeStamp = param['ClientTime']

        InviteInfo = self.mod.getInvite()
        if not InviteInfo or InviteTimeStamp > InviteInfo['EndTime']:
            return Gcore.error(optId, -15007004)

        Invites = [
            InviteInfo["GeneralId1"], InviteInfo["GeneralId2"],
            InviteInfo["GeneralId3"]
        ]
        if GeneralType not in Invites:
            return Gcore.error(optId, -15007001)  #此武将不可招募

        modGeneral = Gcore.getMod('General', self.uid)
        if GeneralType in modGeneral.getGeneralTypeList():
            return Gcore.error(optId, -15007002)  #已有该类型武将

        FreeGeneralHomes = self.mod.getFreeGeneralHomes(InviteTimeStamp)
        if not FreeGeneralHomes:
            return Gcore.error(optId, -15007003)  #没有剩余的点将台

        GeneralInfo = Gcore.getCfg('tb_cfg_general', key=GeneralType)
        InviteCostType = GeneralInfo["InviteCostType"]
        InviteCost = GeneralInfo["InviteCost"]

        #开始支付流程
        print 'InviteCostType', InviteCostType
        print 'InviteCost', InviteCost
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, InviteCostType, InviteCost, classMethod,
                              param)
        if pay < 0:
            return Gcore.error(optId, -15007995)  #支付失败

        GeneralId = modGeneral.addNewGeneral(GeneralType,
                                             min(FreeGeneralHomes),
                                             InviteTimeStamp)

        recordData = {'uid': self.uid, 'ValType': GeneralType, 'Val': 1}  #成就记录
        return Gcore.out(optId,
                         body={
                             "Location": min(FreeGeneralHomes),
                             "GeneralId": GeneralId,
                             "GeneralType": GeneralType
                         },
                         achieve=recordData,
                         mission=recordData)
Example #32
0
    def MoveBuilding(self, param={}):
        '''通用:移动建筑位置'''
        optId = 15901

        BuildingId = param['BuildingId']
        x = param['x']
        y = param['y']
        TimeStamp = param['ClientTime']

        #用户的所有建筑
        AllBuildings = self.mod.getBuildingById(
            fields=['BuildingId', 'BuildingType', 'x', 'y', 'xSize', 'ySize'],
            TimeStamp=TimeStamp)

        AllBuildings2 = []  #除建筑本身外的所有建筑
        tag = False  #玩家是否有该建筑
        for building in AllBuildings:
            if BuildingId == building['BuildingId']:
                tag = True
                xSize = building['xSize']
                if building['BuildingType'] == 1:
                    return Gcore.error(optId, -15901001)  #将军府不能移动
            else:
                AllBuildings2.append(building)
        if not tag:
            return Gcore.error(optId, -15901002)  #不是该玩家的建筑,无法移动

        del AllBuildings
        #已经被建筑占用的坐标
        modMap = Gcore.getMod('Map', self.uid)
        UsedCoords = modMap.cacUsedCoords(AllBuildings2)

        #所有可用坐标
        UsefulCoords = modMap.getAllUsefulCoords()

        #要使用的坐标
        NeededCoords = modMap.getCoords(x, y, xSize)

        #检查坐标是否可用
        for CoordTpl in NeededCoords:
            if CoordTpl in UsedCoords or CoordTpl not in UsefulCoords:
                #print 'CoordTpl',CoordTpl
                #print 'UsedCoords',UsedCoords
                return Gcore.error(optId, -15901003)  #坐标已被占用

        self.mod.updateBuildingById({"x": x, "y": y}, BuildingId)
        recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1}  #成就、任务记录
        return Gcore.out(optId,
                         body={
                             "x": x,
                             "y": y,
                             "BuildingId": BuildingId
                         },
                         mission=recordData)
Example #33
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 #34
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 #35
0
    def FullAddSoldier(self, param={}):
        '''填满兵营或工坊的剩余训练空间'''
        optId = 15031
        
        BuildingId = param['BuildingId']
        TimeStamp = param['ClientTime']
        
        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15031001) #玩家没有该建筑
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15031002) #建筑正在建造
        if BuildingInfo['BuildingType'] not in (6, 8):
            return Gcore.error(optId, -15031003) #建筑不是兵营或工坊

        modCamp = Gcore.getMod('Building_camp', self.uid) 
        spawn_detail= modCamp.getSoldierStorage(BuildingInfo, TimeStamp)

        MaxNum = Gcore.getCfg('tb_cfg_building_up',
                              (BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel']),
                              'MakeValue')
        buy_cnt = MaxNum - spawn_detail['StorageNum']
        print '兵营或工坊的最大数量', MaxNum
        print '当前时刻的数量', spawn_detail['StorageNum']
        print '购买数量', buy_cnt
        
        if buy_cnt < 0:
            return Gcore.error(optId, -15031004) #兵营或工坊已满
        elif buy_cnt > 0:
            coin_need = calSpeedCost(3, buy_cnt)
            class_method = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
            modCoin = Gcore.getMod('Coin', self.uid)
            pay = modCoin.PayCoin(optId, 1, coin_need, class_method, param)
            if pay < 0:
                return Gcore.error(optId, -15031005) #支付失败
            
            #将兵营置满
            modCamp.fullAddSoldier(BuildingId, BuildingInfo['BuildingType'], 
                                   BuildingInfo['BuildingRealLevel'],
                                   max(spawn_detail['LastChangedTime'], TimeStamp),
                                   TimeStamp)
        else:
            pay = 0

        body = {}
        body['StorageNum'] = MaxNum
        body['BuyCnt'] = buy_cnt
        body['GoldenCoinCost'] = pay
        body['TimeStamp'] = TimeStamp
        
        return Gcore.out(optId, body=body)
Example #36
0
    def UpgradeWallTech(self,p={}):
        '''城墙升级科技'''
        optId = 15054
        techType = p.get('TechType')  
        buildingId = p.get('BuildingId')
        now = time.time() 
        techCategory = 1
        #判断传入参数是否合法

        techCfg = Gcore.getCfg('tb_cfg_wall_school')
        ts = [k[0] for k in techCfg.keys()]
        if techType<200 or techType not in ts:
            return Gcore.error(optId,-15054999)  

        
        #获院建筑信息
        building = Gcore.getMod('Building',self.uid).getBuildingById(buildingId)
        if not building or building.get('BuildingType')!=19:
            return Gcore.error(optId,-15054901)#建筑不存在
        
        bookLevel = building.get('BuildingRealLevel')
        flag = self.mod.getUpgradingTech(buildingId)
        if flag:
            return Gcore.error(optId,-15054001)#学习占用中
        
        tech = self.mod.getTech(techCategory,techType)
        techLevel = tech.get('TechLevel')
        techMaxLevel = self.mod.getTechMaxLevel(techCategory,techType,bookLevel)
        if techMaxLevel is None or techLevel >= techMaxLevel:
            return Gcore.error(optId,-15054002)#城墙等级不足
        
        techCfg = techCfg.get((techType,techLevel+1))#获取科技类型与等级配置
        
        needTime = techCfg.get('LearnTime')
        itemId = techCfg.get('ItemIdNeed')
        itemNum = techCfg.get('ItemNeedNeed')
        
        flag = Gcore.getMod('Bag',self.uid).useItems(itemId,itemNum)

        if flag:#支付成功
            data = {'TechLevel':techLevel+1,
                    'LastStartTime':now,
                    'LastEndTime':now+needTime,
                    'BuildingId':buildingId}
            
            self.mod.updateTech(techCategory,techType,data)
        else:
            return Gcore.error(optId,-15054003)#道具数量不足
        
        tech = self.mod.getUpgradingTech(buildingId)
        return Gcore.out(optId,{'Tech':tech})
Example #37
0
    def MoveGoods(self,p={}):
        '''调整物品'''
        optId = 13062
        pFrom = p['From']
        pTo = p['To']
        bagSize = self.mod.getBagSize()
        if not(0<pFrom<=bagSize) or not(0<pTo<=bagSize):
            return Gcore.error(optId, -13062001)#背包位置不合法
        
        if pFrom == pTo:#会删除道具
            return Gcore.out(optId,{})
        
        gFrom = self.mod.getFromPosition(pFrom)
        gTo = self.mod.getFromPosition(pTo)
        if not gFrom:
            return Gcore.error(optId,-13062002)#当前没有物品
        
        #改变物品位置
        if not gTo:#将物品移动到空格
#             print '移动到',pFrom,pTo
#             print 'F',gFrom
            self.mod.updateBag(gFrom['BagId'],{'Position':pTo})
            
        #相同道具叠加
        elif gFrom['GoodsType']==gTo['GoodsType']==2 and gFrom['GoodsId']==gTo['GoodsId']:
#             print '道具叠加',pFrom,pTo
#             print 'F',gFrom
#             print 'T',gTo
            
            gFromNum = gFrom['GoodsNum']
            gToNum = gTo['GoodsNum']
            gToMax = Gcore.getCfg('tb_cfg_item',gTo['GoodsId'],'OverlayNum')
            if gToNum<gToMax:
                gToNum = gToNum+gFromNum
                if gToNum>gToMax:
                    gFromNum = gToNum-gToMax
                    gToNum = gToMax
                else:
                    gFromNum = 0
                self.mod.updateBag(gTo['BagId'],{'GoodsNum':gToNum})
                self.mod.updateBag(gFrom['BagId'],{'GoodsNum':gFromNum})     
                 
        #两物品交换位置   
        else:
#             print '交换位置',pFrom,pTo
#             print 'F',gFrom
#             print 'T',gTo
            
            self.mod.updateBag(gFrom['BagId'],{'Position':pTo})
            self.mod.updateBag(gTo['BagId'],{'Position':pFrom})
        return Gcore.out(optId,{})
Example #38
0
    def GetReward(self, p={}):
        '''领取奖励'''
        optId = 15112
        achieveType = p['AchieveType']

        achiCfg = Gcore.getCfg('tb_cfg_achieve', achieveType)
        if achiCfg is None:
            return Gcore.error(optId, -15112001)  #无此项成就

        achieve = self.mod.getAchieveInfo(achieveType)  #查询成就信息
        current = achieve.get('CurrentAchieve')
        currentAchieveId = achieve.get('CurrentAchieveId')
        rewAchieveId = achieve.get('NextAchieveId')  #领取的奖励
        rewAchieve = achiCfg.get(rewAchieveId).get('AchieveRequire')
        if current < rewAchieve:
            return Gcore.error(optId, -15112002)  #成就未达成

        if achieve['Finished'] == 1:
            return Gcore.out(optId, {
                'Finished': 1,
                'GetAchieve': rewAchieveId
            })  #成就已完成

        maxAchieveId = max(achiCfg.keys())  #最大成就值

        if rewAchieveId == maxAchieveId:  #成就完成
            data = {
                'NextAchieveId': rewAchieveId,
                'Finished': 1,
                'CurrentAchieveId': rewAchieveId
            }
            mission = {'uid': self.uid, 'ValType': 0, 'Val': 1}  #任务记录
        else:
            data = {
                'NextAchieveId': rewAchieveId + 1,
                'Finished': 0,
                'CurrentAchieveId': rewAchieveId
            }
            mission = {}
        updateWhere = 'UserId=%s AND AchieveType=%s AND CurrentAchieveId=%s' % (
            self.uid, achieveType, currentAchieveId)
        if self.mod.updateAchieveByWhere(data, updateWhere):
            achiCfg = achiCfg.get(rewAchieveId)
            rewardType = achiCfg.get('RewardType')
            rewardValue = achiCfg.get('AchieveReward')
            coinMod = Gcore.getMod('Coin', self.uid)
            coinMod.GainCoin(optId, rewardType, rewardValue,
                             'Building_homeUI.GetReward', p)
            return Gcore.out(optId, data, mission=mission)
        else:
            return Gcore.error(optId, -15112996)  #操作失败
Example #39
0
    def ReceiveAttachments(self,param={}):   
        ''' 将附件某东西添加给玩家
        @param param['AttachmentId']  表示附件 Id
        '''
        optId = 18005
        classMethod = '%s,%s'%(self.__class__.__name__,sys._getframe().f_code.co_name)
        attachIds=param['AttachIds']
        if not attachIds:
            return Gcore.error(optId,-18005999)

        result=self.mod.receiveAttachment(attachIds,optId,classMethod,param)
        if result==-1:
            return Gcore.error(optId,-18005001)#背包已满了
        return Gcore.out(optId,{'Result':result})
Example #40
0
 def DeleteGeneral(self, param = {}):
     '''点将台:遣散一名武将'''
     optId = 15012
     
     GeneralId = param['GeneralId']
     
     modGeneral = Gcore.getMod('General', self.uid)
     stat = modGeneral.deleteGeneralById(GeneralId)
     if stat == -1:
         return Gcore.error(optId, -15012001) #用户没有该武将
     if stat == -2:
         return Gcore.error(optId, -15012002) #武将身上有装备,无法遣散
     
     return Gcore.out(optId, {})
Example #41
0
    def SpeedupInvite(self, param={}):
        '''招贤馆:黄金加速刷新'''
        optId = 15008

        BuildingId = param['BuildingId']
        SpeedUpTimeStamp = param['ClientTime']

        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId,
                                                   TimeStamp=SpeedUpTimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15008901)  #用户没有该建筑
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15008902)  #建筑正在建造
        if BuildingInfo['BuildingType'] != 13:
            return Gcore.error(optId, -15008903)  #该建筑不是招贤馆

        InviteInfo = self.mod.getInvite()
        if not InviteInfo or InviteInfo['EndTime'] < SpeedUpTimeStamp:
            return Gcore.error(optId, -15008001)  #没有招募记录

        #获取加速次数
        SpeedCount = self.mod.cacSpeedCount(InviteInfo['SpeedCount'],
                                            InviteInfo['LastSpeedDate'],
                                            SpeedUpTimeStamp)
        SpeedCount += 1

        coinValue = 5  #读配置

        #开始支付流程
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, 1, coinValue, classMethod, param)
        if pay < 0:
            return Gcore.error(optId, -15008995)  #支付失败

        BuildingLevel = BuildingInfo['BuildingRealLevel']
        ChosenGenerals = self.mod.chooseGenerals()
        self.mod.updateInvite(ChosenGenerals, BuildingLevel, SpeedUpTimeStamp,
                              SpeedCount)

        RemainedTime = Gcore.getCfg('tb_cfg_building_up', (13, BuildingLevel),
                                    'RefreshValue')
        RetDic = {}
        RetDic["CostValue"] = coinValue
        RetDic["NextCostValue"] = coinValue
        RetDic["RemainedTime"] = RemainedTime
        RetDic["Generals"] = ChosenGenerals
        return Gcore.out(optId, RetDic)
Example #42
0
 def Say(self,para={}):
     '''发送聊天信息
     @para : Channel => int 聊天类型:1,世界。2,势力。3,军团。4,私聊。5,系统。6,喇叭。 
             7, 系统公告(用于GM发布系统公告用)。8,活动。9,广播
     @para : Content => string 消息体
     @para : ToName => int or str 消息接受者(用于私聊)
     @note : 需要注意前玩家在游戏中 改变军团(退出或加入)时要更新Gcore.StorageUser['club']
     '''
     optId = 11001
     #print 'say',para
     channel=para.get('Channel')
     content=para.get('Content')
     toName=para.get('ToName')
     #re=1
     re=self.mod.say(optId, channel,content,toName)
     if re==-1:
         return Gcore.error(optId,-11001001)#聊天间隔限制
     elif re==-2:
         return Gcore.error(optId,-11001002)#消息未通过验证
     elif re==-3:
         return Gcore.error(optId,-11001003)#发送对象不在线
     elif re==-4:
         return Gcore.error(optId,-11001004)#喇叭使用条件不足
     elif re==-5:
         return Gcore.error(optId,-11001999)#聊天类型错误
     elif re==-6:
         return Gcore.error(optId,-11001005)#不能私聊自己
     elif re==-7:
         return Gcore.error(optId,-11001006)#权限不足
     elif re==-8:
         return Gcore.error(optId,-11001007)#被禁言
     else:
         #return Gcore.out(optId,{'Result':re})
         return Gcore.out(optId)
Example #43
0
 def Say(self, para={}):
     '''发送聊天信息
     @para : Channel => int 聊天类型:1,世界。2,势力。3,军团。4,私聊。5,系统。6,喇叭。 
             7, 系统公告(用于GM发布系统公告用)。8,活动。9,广播
     @para : Content => string 消息体
     @para : ToName => int or str 消息接受者(用于私聊)
     @note : 需要注意前玩家在游戏中 改变军团(退出或加入)时要更新Gcore.StorageUser['club']
     '''
     optId = 11001
     #print 'say',para
     channel = para.get('Channel')
     content = para.get('Content')
     toName = para.get('ToName')
     #re=1
     re = self.mod.say(optId, channel, content, toName)
     if re == -1:
         return Gcore.error(optId, -11001001)  #聊天间隔限制
     elif re == -2:
         return Gcore.error(optId, -11001002)  #消息未通过验证
     elif re == -3:
         return Gcore.error(optId, -11001003)  #发送对象不在线
     elif re == -4:
         return Gcore.error(optId, -11001004)  #喇叭使用条件不足
     elif re == -5:
         return Gcore.error(optId, -11001999)  #聊天类型错误
     elif re == -6:
         return Gcore.error(optId, -11001005)  #不能私聊自己
     elif re == -7:
         return Gcore.error(optId, -11001006)  #权限不足
     elif re == -8:
         return Gcore.error(optId, -11001007)  #被禁言
     else:
         #return Gcore.out(optId,{'Result':re})
         return Gcore.out(optId)
Example #44
0
    def DeleteGeneral(self, param={}):
        '''点将台:遣散一名武将'''
        optId = 15012

        GeneralId = param['GeneralId']

        modGeneral = Gcore.getMod('General', self.uid)
        stat = modGeneral.deleteGeneralById(GeneralId)
        if stat == -1:
            return Gcore.error(optId, -15012001)  #用户没有该武将
        if stat == -2:
            return Gcore.error(optId, -15012002)  #武将身上有装备,无法遣散

        return Gcore.out(optId, {})
Example #45
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 #46
0
    def MailList(self, param={}):
        '''
                    收件箱/发件箱列表
        @param param['MailType']=1 表示收件箱
               param['MailType']=2 表示发件箱 
        '''
        optId = 18003
        mailType = int(param['MailType'])
        page = int(param['Page'])  #页码
        if not page:  #默认为第一页
            page = 1
        if mailType not in (1, 2):
            return Gcore.error(optId, -18003999)  #MailType值不对
        mailCfg = Gcore.loadCfg(Gcore.defined.CFG_MAIL)
        pagePerNum = int(mailCfg['MailShowPerPageMax'])  #每页的邮件数
        mailCount = int(self.mod.mailCountByType(mailType))  #收件箱/发件箱中邮件总数
        mailDatas = self.mod.getMailList(mailType, page,
                                         pagePerNum)  #每页显示的邮件数据

        subjShowMax = mailCfg['SubjectShowMax']  #邮件主题显示最大长度
        self.mod.finMailDatas(mailDatas, subjShowMax)
        totalPage = int(math.ceil(1.0 * mailCount / pagePerNum))

        body = {
            'mailDatas': mailDatas,
            'page': page,
            'mailCount': mailCount,
            'totalpage': totalPage
        }

        return Gcore.out(optId, body=body)
Example #47
0
 def SignIn(self, param={}):
     '''补签 操作'''
     optId = 23007
     classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
     date = param['Date']
     re = self.mod.signin(optId, classMethod, date)
     if re == -1:
         return Gcore.error(optId, -23007001)#该日期已签
     if re == -2:
         return Gcore.error(optId, -23007002)#日期错误
     if re == -3:
         return Gcore.error(optId, -23007003)#没有重签次数
     if re == -4:
         return Gcore.error(optId, -23007004)#货币不足
     
     return Gcore.out(optId, {'Cost': re})
Example #48
0
    def WarSweepNew(self, para={}):
        '''新扫荡'''
        optId = 91005
        if not self.mod._checkGeneralSoldier():
            return Gcore.error(optId, -91005001)
        if para['SweepTimes'] <= 0:
            return Gcore.error(optId, -91005997)
        re = self.mod.warSweepNew(para['WarId'], para['SweepTimes'])
        if not re:
            return Gcore.error(optId, -91005002)
        gevent.sleep(0.5)
        body = {}
        RestPoint, MaxPoint = self.mod.getActPoint()
        body['RestPoint'] = RestPoint

        return Gcore.out(optId, body)
Example #49
0
    def CheckFriend(self, param={}):
        '''查看好友'''
        optId = 19007
        friendUserId = param['FriendUserId']
        if not self.mod.validateUser(friendUserId):
            return Gcore.error(optId, -19007001)  #用户不存在

        player = Gcore.getMod('Player', friendUserId)
        fileds = [
            'UserId', 'NickName', 'UserLevel', 'VipLevel', 'UserIcon',
            'UserHonour', 'UserCamp'
        ]
        result = player.getUserBaseInfo(fileds)  #获得基本信息
        result['Rank'] = player.getHonRankNum(result)

        buildingClub = Gcore.getMod('Building_club', friendUserId)
        cId = buildingClub.getUserClubId()
        clubInfo = buildingClub.getClubInfo(cId, 'ClubName')
        if clubInfo:
            result['ClubName'] = clubInfo['ClubName']  #获得军团名字
        else:
            result['ClubName'] = ''
        general = Gcore.getMod('General', friendUserId)
        generalNum = general.getMyGenerals('count(1) as gNum')
        result['GeneralNum'] = generalNum[0]['gNum']  #获得武将个数

        buildingNum = self.mod.getBuildingCount(friendUserId)
        result['BuildingNum'] = buildingNum  #获得建筑数量

        return Gcore.out(optId, result)
Example #50
0
  def CleanWallDefense(self,p={}):
      '''回收损毁的防御工事'''
      optId = 92012
      CoinValue = self.mod.clearWallDefense()
      if CoinValue:
          Gcore.getMod('Coin',self.uid).GainCoin(optId,2,CoinValue,'WallUI.CleanWallDefense',p)#返回军资
          reward = self.mod.getWallBoxReward() #获取遗落宝箱的奖励
          if reward:#有奖励
              rewardType = reward['RewardType']
              goodsId = reward['GoodsId']
              goodsNum = reward['GoodsNum']
              ids = Gcore.getMod('Reward',self.uid).reward(optId,p,rewardType,goodsId,goodsNum)
              #reward['WillGet'] = 1
              if rewardType==1:
                  if isinstance(ids,list):
                      reward['EquipIds'] = ids
                  else:
                      reward['EquipIds'] = []
              
          else:#无奖励
              #reward = {'WillGet':0}
              reward = {}
 
          recordData = {'uid':self.uid,'ValType':0,'Val':1,'WillGet':reward.get('WillGet')}
          body = {"CoinType":2,"CoinValue":CoinValue,"Reward":reward}
          return Gcore.out(optId,body,mission=recordData)
      else:
          return Gcore.error(optId,-92012001) #没有可回收的防御工事
Example #51
0
 def checkLogin(self,ckey,optId,optKey,para):
     """登录验证,不同于城市场景的登录"""
     from sgLib.pyMcrypt import TokenDecode
     
     #tokenDict: {u'TotalServiceId': u'42', u'LoginMode': 2, u'PlayerId': 0, u'LoginVersion': 101, u'Lan': 1, u'LockTime': 1367994093}
     response = None
     try:
         objToken = TokenDecode()
         tokenDict = objToken.getTokenMsg(para.get("pyKey"))
         print 'tokenDict > ',tokenDict
         if not self.Clients[ckey]['uid']:
             c = Login()
             uid = c.getUserIdByAccount(tokenDict.get('TotalServiceId'))
             self.Clients[ckey]['uid'] = uid
             print 'Player %s logined'%self.Clients[ckey]['uid']
         else:
             print 'Developer %s logined'%self.Clients[ckey]['uid']
         
         uid = self.Clients[ckey]['uid']
         Gcore.onlineUser[uid] = 1
         
         response = Gcore.out(optId,{'ServerTime':time.time()})
         #Gcore.setUserData(uid, {'Channel':self.Clients[ckey]['Channel']}) #储存用户channel 推送需要
     except Exception:
         pass
     
     if not response:
         response = Gcore.error(optId,-10001003) #登录验证失败
     
     response['opt_key'] = optKey
     self.Send(ckey,response) 
Example #52
0
    def ReceiveAttachments(self, param={}):
        ''' 将附件某东西添加给玩家
        @param param['AttachmentId']  表示附件 Id
        '''
        optId = 18005
        classMethod = '%s,%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        attachIds = param['AttachIds']
        if not attachIds:
            return Gcore.error(optId, -18005999)

        result = self.mod.receiveAttachment(attachIds, optId, classMethod,
                                            param)
        if result == -1:
            return Gcore.error(optId, -18005001)  #背包已满了
        return Gcore.out(optId, {'Result': result})
Example #53
0
 def WarSweepNew(self,para={}):
     '''新扫荡'''
     optId = 91005
     if not self.mod._checkGeneralSoldier():
         return Gcore.error(optId, -91005001)
     if para['SweepTimes']<=0:
         return Gcore.error(optId, -91005997)
     re = self.mod.warSweepNew( para['WarId'], para['SweepTimes'] )
     if not re:
         return Gcore.error(optId,-91005002)
     gevent.sleep(0.5)
     body ={}
     RestPoint,MaxPoint = self.mod.getActPoint()
     body['RestPoint'] = RestPoint
     
     return Gcore.out(optId,body)
Example #54
0
    def CheckFriend(self, param={}):
        """查看好友"""
        optId = 19007
        friendUserId = param["FriendUserId"]
        if not self.mod.validateUser(friendUserId):
            return Gcore.error(optId, -19007001)  # 用户不存在

        player = Gcore.getMod("Player", friendUserId)
        fileds = ["UserId", "NickName", "UserLevel", "VipLevel", "UserIcon", "UserHonour", "UserCamp"]
        result = player.getUserBaseInfo(fileds)  # 获得基本信息
        result["Rank"] = player.getHonRankNum(result)

        buildingClub = Gcore.getMod("Building_club", friendUserId)
        cId = buildingClub.getUserClubId()
        clubInfo = buildingClub.getClubInfo(cId, "ClubName")
        if clubInfo:
            result["ClubName"] = clubInfo["ClubName"]  # 获得军团名字
        else:
            result["ClubName"] = ""
        general = Gcore.getMod("General", friendUserId)
        generalNum = general.getMyGenerals("count(1) as gNum")
        result["GeneralNum"] = generalNum[0]["gNum"]  # 获得武将个数

        buildingNum = self.mod.getBuildingCount(friendUserId)
        result["BuildingNum"] = buildingNum  # 获得建筑数量

        return Gcore.out(optId, result)
Example #55
0
 def GetBaseInfo(self,param={}):
     optId = 13003
     userId=param['UserId']
     modPlay=Gcore.getMod('Player',userId)
     
     fileds=['NickName','UserLevel','VipLevel','UserIcon','UserHonour','UserCamp','UserExp']
     result= modPlay.getUserBaseInfo(fileds)
     if result is None:
         return Gcore.error(optId,-13003001)#用户不存在
     
     result['Rank']=modPlay.getHonRankNum(result)
     
     buildingClub = Gcore.getMod('Building_club',userId)
     cId=buildingClub.getUserClubId()
     clubInfo=buildingClub.getClubInfo(cId,'ClubName')
     if clubInfo:
         result['ClubName']=clubInfo['ClubName']     #获得军团名字
     else:
         result['ClubName']=''
         
     general=Gcore.getMod('General', userId)
     generalNum=general.getMyGenerals('count(1) as gNum')
     result['GeneralNum']=generalNum[0]['gNum'] #获得武将个数
     
     modFriend=Gcore.getMod('Friend',userId)
     buildingNum=modFriend.getBuildingCount(userId)
     result['BuildingNum']=buildingNum 
     
     return Gcore.out(optId,result)
Example #56
0
    def MoveElement(self, p={}):
        '''批量移动布防内的元素'''
        optId = 92002
        ''' 参数例子:
        p = {}
        p['DefenseInfo'] = [
                             {'WallDefenseId':4,'x':1,'y':1,'xSize':1,'ySize':3},
                             {'WallDefenseId':5,'x':11,'y':13,'xSize':2,'ySize':2},
                             ]
        p['GeneralInfo'] = [
                             {'GeneralId':1,'x':8,'y':14},
                             {'GeneralId':2,'x':4,'y':43},
                             ]
        '''
        #        if 'DefenseInfo' in p:
        #            WallDefenseIds = [ r['WallDefenseId'] for r in p['DefenseInfo'] ]
        #
        #            rows = self.mod.getDefenseInfo(WallDefenseIds)
        #            for row in rows:
        #                SoldierType = row['SoldierType']
        #                xSize = row['xSize']
        #                ySize = row['ySize']
        #                Size = Gcore.getCfg('tb_cfg_soldier',SoldierType,'Size')
        #
        #                if str(xSize)+'*'+str(ySize)!=Size and str(ySize)+'*'+str(xSize)!=Size:
        #                    return Gcore.error(optId,-92002998) #非法操作
        #                #@todo 坐标验证

        result = self.mod.moveElement(p)
        if not result:
            return Gcore.error(optId, -92002997)  #系统错误
        else:
            return Gcore.out(optId)
Example #57
0
    def MoveElement(self,p={}):
        '''批量移动布防内的元素'''
        optId = 92002
        ''' 参数例子:
        p = {}
        p['DefenseInfo'] = [
                             {'WallDefenseId':4,'x':1,'y':1,'xSize':1,'ySize':3},
                             {'WallDefenseId':5,'x':11,'y':13,'xSize':2,'ySize':2},
                             ]
        p['GeneralInfo'] = [
                             {'GeneralId':1,'x':8,'y':14},
                             {'GeneralId':2,'x':4,'y':43},
                             ]
        '''
#        if 'DefenseInfo' in p:
#            WallDefenseIds = [ r['WallDefenseId'] for r in p['DefenseInfo'] ]
#            
#            rows = self.mod.getDefenseInfo(WallDefenseIds)
#            for row in rows:
#                SoldierType = row['SoldierType']
#                xSize = row['xSize']
#                ySize = row['ySize']
#                Size = Gcore.getCfg('tb_cfg_soldier',SoldierType,'Size')
#
#                if str(xSize)+'*'+str(ySize)!=Size and str(ySize)+'*'+str(xSize)!=Size:
#                    return Gcore.error(optId,-92002998) #非法操作
#                #@todo 坐标验证
                
        result = self.mod.moveElement(p)
        if not result:
            return Gcore.error(optId,-92002997) #系统错误
        else:
            return Gcore.out(optId)