Example #1
0
    def findOutFighter(self, num=10, rowUser=None):
        '''跨服查找可攻城对象'''
        #print ' --- findOutFighter ---'
        try:
            if not rowUser:
                rowUser = self.getUserInfo(['UserCamp', 'UserLevel'])
            url = Gcore.loadCoreCfg('PlatformUrl')
            Post = {}
            Post['ServerId'] = Gcore.getServerId()
            Post['LOCKKEY'] = TokenDecode().makeLockKey()
            Post['FUNC'] = "FindUI.FindFighter"
            Post['PARAM'] = {
                'FromServerId': Gcore.getServerId(),
                'UserCamp': rowUser['UserCamp'],
                'UserLevel': rowUser['UserLevel'],
                'GetNum': num,
            }

            url += '?MSG=' + json.dumps(Post)
            #print 'findOutFighter>>',url
            req = urllib2.Request(url)
            f = urllib2.urlopen(req)
            response = f.read()
            lis = response.split('@.@')
            return json.loads(lis[1])
        except:
            return []
Example #2
0
    def GetHold(self, param={}):
        '''
        @旧:我的藩国(如果我有主人就显示主人信息): 获取主人和奴隶的信息
        @新:显示我的藩国列表
        '''
        optId = 15123

        #holder = self.mod.getHolder()
        #if not holder:
        if True:
            holder = {"hServerId": 0, "hUserId": 0}

            Slaves = self.mod.getHold()
            for Slave in Slaves:
                suid, ssid = Slave['UserId'], Slave.get(
                    'ServerId', Gcore.getServerId())
                stat = self.mod.isMyHold(suid, ssid)
                if not stat:
                    Slave['Jcoin'], Slave['Gcoin'] = 0, 0
                else:
                    Slave['Jcoin'], Slave['Gcoin'] = stat
                Slave.setdefault('ServerId', Gcore.getServerId())
        else:
            Slaves = []

        return Gcore.out(optId, {'Holder': holder, 'Holds': Slaves})
Example #3
0
    def GetHold(self, param={}):
        '''
        @旧:我的藩国(如果我有主人就显示主人信息): 获取主人和奴隶的信息
        @新:显示我的藩国列表
        '''
        optId = 15123
        
        #holder = self.mod.getHolder()
        #if not holder:
        if True:
            holder = {"hServerId":0, "hUserId":0}
            
            Slaves = self.mod.getHold()
            for Slave in Slaves:
                suid, ssid = Slave['UserId'], Slave.get('ServerId', Gcore.getServerId())
                stat = self.mod.isMyHold(suid, ssid)
                if not stat:
                    Slave['Jcoin'], Slave['Gcoin'] = 0, 0
                else:
                    Slave['Jcoin'], Slave['Gcoin'] = stat
                Slave.setdefault('ServerId', Gcore.getServerId())
        else:
            Slaves = []
 
        return Gcore.out(optId, {'Holder':holder, 'Holds':Slaves})
Example #4
0
 def findOutFighter(self,num=10,rowUser=None):
     '''跨服查找可攻城对象'''
     #print ' --- findOutFighter ---'
     try:
         if not rowUser:
             rowUser = self.getUserInfo(['UserCamp','UserLevel'])
         url =  Gcore.loadCoreCfg('PlatformUrl')
         Post = {}
         Post['ServerId'] = Gcore.getServerId()
         Post['LOCKKEY'] = TokenDecode().makeLockKey()
         Post['FUNC'] ="FindUI.FindFighter" 
         Post['PARAM'] ={
                         'FromServerId':Gcore.getServerId(),
                         'UserCamp':rowUser['UserCamp'],
                         'UserLevel':rowUser['UserLevel'],
                         'GetNum':num,
                         }
         
         url+='?MSG='+json.dumps(Post)
         #print 'findOutFighter>>',url
         req = urllib2.Request(url)
         f = urllib2.urlopen(req)
         response = f.read()
         lis = response.split('@.@')
         return json.loads(lis[1])
     except:
         return []
Example #5
0
 def findSiege(self, para):
     '''创建攻城 查找攻城战斗
     @param fromType': 1, #1查找 2复仇 3反抗 4抢夺 (#@todo战斗结束后具体效果还没做)
     @param serverId': 0, #1查找时不需要
     @param targetUserId':  0,  #1查找时不需要
      '''
     print 'ps findSiege ',para
     
     optId = 93001
     initResult = self.mod.initWar(0)
     if initResult<0: #重复@todo优化
         if initResult==-1:
             return Gcore.error(optId,-93001001) #尚未派兵出征,请先布阵
         elif initResult==-2:
             return Gcore.error(optId,-93001008) #剩余行动力不足
         elif initResult==-3:
             return Gcore.error(optId,-93001010) #战役未达到,不可攻打
         elif initResult==-4:
             return Gcore.error(optId,-93001009) #等级未达到,不可攻城
         else:
             return Gcore.error(optId,-93001997) #系统错误
         
     if para.get('serverId') == Gcore.getServerId() and para.get('targetUserId') == self.uid:
         return Gcore.error(optId,-93001002) #不可攻打自己
     
     try:
         body = self.mod.findSiege(para) #查找攻城
     except Exception,e:
         if Gcore.TEST:
             raise
         return Gcore.error(optId,-93001997,{'Exception':str(e)} ) #系统错误
Example #6
0
    def findSiege(self, para):
        '''创建攻城 查找攻城战斗
        @param fromType': 1, #1查找 2复仇 3反抗 4抢夺 (#@todo战斗结束后具体效果还没做)
        @param serverId': 0, #1查找时不需要
        @param targetUserId':  0,  #1查找时不需要
         '''
        print 'ps findSiege ', para

        optId = 93001
        initResult = self.mod.initWar(0)
        if initResult < 0:  #重复@todo优化
            if initResult == -1:
                return Gcore.error(optId, -93001001)  #尚未派兵出征,请先布阵
            elif initResult == -2:
                return Gcore.error(optId, -93001008)  #剩余行动力不足
            elif initResult == -3:
                return Gcore.error(optId, -93001010)  #战役未达到,不可攻打
            elif initResult == -4:
                return Gcore.error(optId, -93001009)  #等级未达到,不可攻城
            else:
                return Gcore.error(optId, -93001997)  #系统错误

        if para.get('serverId') == Gcore.getServerId() and para.get(
                'targetUserId') == self.uid:
            return Gcore.error(optId, -93001002)  #不可攻打自己

        try:
            body = self.mod.findSiege(para)  #查找攻城
        except Exception, e:
            if Gcore.TEST:
                raise
            return Gcore.error(optId, -93001997, {'Exception': str(e)})  #系统错误
Example #7
0
    def CreatedPlayer(self, accountId):
        try:
            url = Gcore.loadCoreCfg('PlatformUrl')
            Post = {}
            Post['ServerId'] = Gcore.getServerId()
            Post['LOCKKEY'] = TokenDecode().makeLockKey()
            Post['FUNC'] = "FindUI.CreatedPlayer"
            Post['PARAM'] = {
                'FromServerId': Gcore.getServerId(),
                'AccountId': accountId,
            }

            url += '?MSG=' + json.dumps(Post)
            #print 'findOutFighter>>',url
            req = urllib2.Request(url)
            f = urllib2.urlopen(req)
            response = f.read()
            lis = response.split('@.@')
            return json.loads(lis[1])
        except:
            pass
Example #8
0
 def CreatedPlayer(self,accountId):
     try:
         url =  Gcore.loadCoreCfg('PlatformUrl')
         Post = {}
         Post['ServerId'] = Gcore.getServerId()
         Post['LOCKKEY'] = TokenDecode().makeLockKey()
         Post['FUNC'] ="FindUI.CreatedPlayer" 
         Post['PARAM'] ={
                         'FromServerId':Gcore.getServerId(),
                         'AccountId':accountId,
                         }
         
         url+='?MSG='+json.dumps(Post)
         #print 'findOutFighter>>',url
         req = urllib2.Request(url)
         f = urllib2.urlopen(req)
         response = f.read()
         lis = response.split('@.@')
         return json.loads(lis[1])
     except:
         pass
Example #9
0
 def becomehold(self,para):
     '''协议号1: 被设置为藩国
     @todo 收集一下资源,推送给前端被设为藩国
     '''
     uid, hid, hsid, htime = int(para['GiverId']), int(para['HolderId']), int(para['HolderServerId']), int(para['EndTime'])
     update_dic = {}
     update_dic['HolderId'] = hid
     update_dic['HolderServerId'] = hsid
     update_dic['HoldEndTime'] = htime
     self.db.update('tb_user', update_dic, 'UserId="%s"'%uid)
     #纳贡记录
     arr = {"UserId":uid, "HolderId":hid, "HolderServerId":hsid, "Jcoin":0, "Gcoin":0, "LastGiveTime":htime}
     self.db.insert('tb_hold_log', arr)
     #反抗进度
     arr = {"UserId":uid, "HolderId":hid, "HolderServerId":hsid,
            "ProcessTotal":0, "RevengeCount":0, "LastRevengeDate":datetime.date.today()}
     self.db.insert('tb_hold_revenge', arr)
     #如果有藩国的话全部释放掉
     # + 玩家的藩国
     
     holds = Gcore.getMod('Building_hold',uid).getHold()
     for h in holds:
         param = {"typ":2, "uid":h["UserId"], "sid":h.get("ServerId", Gcore.getServerId())}
         Gcore.getUI('Building_hold',uid).SlaveOperand(param)
Example #10
0
    def findPvcTarget(self):
        '''查找攻城对象  @note:硬凑在这里'''
        CrossServer = int(Gcore.loadCoreCfg('CrossServer')) #是否跨服的配置
        print ' -- ps findPvcTarget CrossServer:%s'%CrossServer
        
        N=200 #匹配参考值
        Num = 20 #每次拿10个
        if Gcore.TEST:
            Num = 100
        rowUser = self.getUserInfo(['UserCamp','UserLevel'])
        UserLevel = rowUser['UserLevel']
        UserCamp = rowUser['UserCamp']
        UserLevelFrom = UserLevel-30;
        UserLevelTo = UserLevel+30;
        ServerId = Gcore.getServerId()
        homeList1 = []
        homeList2 = []
        if(UserCamp==1):
            query = " (UserCamp=2 OR UserCamp=3)"
        elif(UserCamp==2):
            query = " (UserCamp=1 OR UserCamp=3)"
        elif(UserCamp==3):
            query = " (UserCamp=1 OR UserCamp=2)"
        
        query+= " AND UserLevel>=%s"%Gcore.loadCfg(9301).get('FightLevel')
        query+= " AND UserId!=%s"%self.uid
        query+= " AND Online=0 AND ProtectEndTime <= UNIX_TIMESTAMP()";
        where = query+' AND UserLevel>=%s AND UserLevel<=%s'%(UserLevelFrom,UserLevelTo)
        M = self.db.count('tb_user',where)
        
        UserLevelFrom2 = UserLevel-5;
        UserLevelTo2 = UserLevel+5;
        where = query+' AND UserLevel>=%s AND UserLevel<=%s'%(UserLevelFrom2,UserLevelTo2)
        for unit in  self.db.out_rand('tb_user','UserId',where,Num):
            homeList1.append([ServerId,unit['UserId']])
            
        print 'findPvcTarget local +-5 > ',self.db.sql
        
        where = query+' AND (UserLevel>=%s AND UserLevel<%s) OR (UserLevel>%s AND UserLevel<=%s)'\
        %(UserLevelFrom,UserLevelFrom2,UserLevelTo2,UserLevelTo)
        for unit in  self.db.out_rand('tb_user','UserId',where,Num):
            homeList2.append([ServerId,unit['UserId']])
            
        print 'findPvcTarget local +-30 > ',self.db.sql
        #print 'homeList1',homeList1
        #print 'homeList2',homeList2
        random.shuffle(homeList1)
        random.shuffle(homeList2)
        
        if M>=N:#不跨服
            crossPercent = 0 #跨服比例
        elif M<=20:
            crossPercent = 100
        elif M>=0.75*N: 
            crossPercent = 25
        elif M>=0.5*N: 
            crossPercent = 50
        elif M>=0.25*N: 
            crossPercent = 75
        else:
            crossPercent = 100

        #print 'crossPercent',crossPercent
        targetList = []
        randPercent = random.randint(1,100)
        #print 'randPercent',randPercent
        
        if randPercent<=crossPercent and CrossServer: #中比例
            y=math.ceil(M/N*Num)
            getNum = Num-y
#            print 'M',M
#            print 'N',N
#            print 'getNum',getNum
            targetList =  Gcore.getMod('Request', self.uid).findOutFighter(getNum,rowUser)
            print 'Request targetList',targetList
        
        #print targetList
        for i in xrange(Num-len(targetList)):
            if len(homeList1)>i:
                targetList.append(homeList1[i])
                if len(targetList)>=Num:
                    break;
            if len(homeList2)>i:
                targetList.append(homeList2[i])
                if len(targetList)>=Num:
                    break;
        #print 'targetList',targetList
        return targetList
Example #11
0
    def findPvcTarget(self):
        '''查找攻城对象  @note:硬凑在这里'''
        CrossServer = int(Gcore.loadCoreCfg('CrossServer'))  #是否跨服的配置
        print ' -- ps findPvcTarget CrossServer:%s' % CrossServer

        N = 200  #匹配参考值
        Num = 20  #每次拿10个
        if Gcore.TEST:
            Num = 100
        rowUser = self.getUserInfo(['UserCamp', 'UserLevel'])
        UserLevel = rowUser['UserLevel']
        UserCamp = rowUser['UserCamp']
        UserLevelFrom = UserLevel - 30
        UserLevelTo = UserLevel + 30
        ServerId = Gcore.getServerId()
        homeList1 = []
        homeList2 = []
        if (UserCamp == 1):
            query = " (UserCamp=2 OR UserCamp=3)"
        elif (UserCamp == 2):
            query = " (UserCamp=1 OR UserCamp=3)"
        elif (UserCamp == 3):
            query = " (UserCamp=1 OR UserCamp=2)"

        query += " AND UserLevel>=%s" % Gcore.loadCfg(9301).get('FightLevel')
        query += " AND UserId!=%s" % self.uid
        query += " AND Online=0 AND ProtectEndTime <= UNIX_TIMESTAMP()"
        where = query + ' AND UserLevel>=%s AND UserLevel<=%s' % (
            UserLevelFrom, UserLevelTo)
        M = self.db.count('tb_user', where)

        UserLevelFrom2 = UserLevel - 5
        UserLevelTo2 = UserLevel + 5
        where = query + ' AND UserLevel>=%s AND UserLevel<=%s' % (
            UserLevelFrom2, UserLevelTo2)
        for unit in self.db.out_rand('tb_user', 'UserId', where, Num):
            homeList1.append([ServerId, unit['UserId']])

        print 'findPvcTarget local +-5 > ', self.db.sql

        where = query+' AND (UserLevel>=%s AND UserLevel<%s) OR (UserLevel>%s AND UserLevel<=%s)'\
        %(UserLevelFrom,UserLevelFrom2,UserLevelTo2,UserLevelTo)
        for unit in self.db.out_rand('tb_user', 'UserId', where, Num):
            homeList2.append([ServerId, unit['UserId']])

        print 'findPvcTarget local +-30 > ', self.db.sql
        #print 'homeList1',homeList1
        #print 'homeList2',homeList2
        random.shuffle(homeList1)
        random.shuffle(homeList2)

        if M >= N:  #不跨服
            crossPercent = 0  #跨服比例
        elif M <= 20:
            crossPercent = 100
        elif M >= 0.75 * N:
            crossPercent = 25
        elif M >= 0.5 * N:
            crossPercent = 50
        elif M >= 0.25 * N:
            crossPercent = 75
        else:
            crossPercent = 100

        #print 'crossPercent',crossPercent
        targetList = []
        randPercent = random.randint(1, 100)
        #print 'randPercent',randPercent

        if randPercent <= crossPercent and CrossServer:  #中比例
            y = math.ceil(M / N * Num)
            getNum = Num - y
            #            print 'M',M
            #            print 'N',N
            #            print 'getNum',getNum
            targetList = Gcore.getMod('Request', self.uid).findOutFighter(
                getNum, rowUser)
            print 'Request targetList', targetList

        #print targetList
        for i in xrange(Num - len(targetList)):
            if len(homeList1) > i:
                targetList.append(homeList1[i])
                if len(targetList) >= Num:
                    break
            if len(homeList2) > i:
                targetList.append(homeList2[i])
                if len(targetList) >= Num:
                    break
        #print 'targetList',targetList
        return targetList
Example #12
0
 def __init__(self, uid, ServerId=None):
     '''@para: ServerId 测试用'''
     self.uid = uid
     self.serverid = ServerId if ServerId else Gcore.getServerId()
     self.encode = Gcore.common.json_encode
     Base.__init__(self, uid)
Example #13
0
    def PlayerInfo(self):
        '''返回获取用户相关资料'''
        startTime = time.time()

        fields = [
            'UserHonour',
            'UserCamp',
            'NickName',
            'VipLevel',
            'BuyMapTimes',
            'WorkerNumber',
            'UserIcon',
            'UserExp',
            'UserLevel',
            'Fighter',
            'FightEndTime',
            'ProtectEndTime',
            'BindAccount',
            'LoginTimes',
            'HolderServerId',
            'HolderId',
            'HoldEndTime',  #我是否有藩国,藩国结束时间
        ]

        userProfile = self.getUserProfile()

        data = self.getUserBaseInfo(fields)
        data['UserId'] = self.uid
        data['ServerId'] = Gcore.getServerId()  #服务器ID
        data['SuserId'] = '%s.%s' % (Gcore.getServerId(), self.uid
                                     )  #服务器ID跟角色ID组成的标志串
        #data['Worker'] =  self.getUserWorker()
        #@todo 添加更多主角信息
        if Gcore.common.nowtime() >= data['FightEndTime']:
            FightRestTime = 0
        else:
            FightRestTime = data['FightEndTime'] - Gcore.common.nowtime()

        data['FightRestTime'] = FightRestTime  #被攻打剩余时间   Fighter - 正在被谁攻打
        data.pop('FightEndTime')

        buildingCfg = Gcore.loadCfg(CFG_BUILDING)
        data['InitJcoin'] = buildingCfg['InitJcoin']
        data['InitGcoin'] = buildingCfg['InitGcoin']

        data['Coin'] = self.getUserCoin()
        data['ServerTime'] = time.time()  #round(time.time(),2)
        data['SoldierLevel'] = Gcore.getMod('Book', self.uid).getTechsLevel(1)
        data['SoldierInfo'] = Gcore.getMod('Building_camp',
                                           self.uid).TouchAllSoldiers()
        data['Equipments'] = Gcore.getMod('Equip', self.uid).getAllValidEquip()
        data['Factor'] = {  #全部系数
            'kLeader': Gcore.loadCfg(
                Gcore.defined.CFG_BATTLE)["kLeaderAddNum"],  #统帅系数 @todo 从配置中读取
        }
        data['Exchange'] = Gcore.loadCfg(Gcore.defined.CFG_ITEM).get(
            'exchange')  #货币兑换比例
        #data['Timezone'] = Gcore.config.CFG_TIMEZONE #时区
        #data['TimezoneDif'] = Gcore.config.CFG_TIMEZONEDIF #格林时间+CFG_TIMEDIF

        data['Timezone'] = Gcore.loadCoreCfg('Timezone')  #时区
        data['TimezoneDif'] = int(
            Gcore.loadCoreCfg('TimezoneDif'))  #格林时间+CFG_TIMEDIF

        data['PVPstartTime'] = Gcore.loadCfg(Gcore.defined.CFG_PVP).get(
            'PVPstartTime')  #将弃用
        data['PVPendTime'] = Gcore.loadCfg(Gcore.defined.CFG_PVP).get(
            'PVPendTime')  #将弃用
        data['PvpTime'] = Gcore.loadCfg(Gcore.defined.CFG_PVP).get('PvpTime')

        #军团信息
        clubInfo = Gcore.getMod('Building_club', self.uid).getMemberInfoByUID(
            self.uid, ['ClubId', 'DevoteCurrent'])  #军团ID
        data['ClubId'] = clubInfo.get('ClubId', 0)
        data['ClubDvo'] = clubInfo.get('DevoteCurrent', 0)
        data['ClubBox'] = Gcore.loadCfg(
            Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost')

        #装备传承花费
        data['DivertCost'] = Gcore.loadCfg(
            Gcore.defined.CFG_EQUIP).get('DivertCost')
        data['DivertCostType'] = Gcore.loadCfg(
            Gcore.defined.CFG_EQUIP).get('DivertCostType')

        data['Inters'] = Gcore.getMod('Building_home',
                                      self.uid).getInters()  #内政

        #获取场景14001 MapUI.getScene()搬过来的
        BuildingInfo = Gcore.getMod('Building', self.uid).getAllBuildingCoord()
        interactGids = Gcore.getMod(
            'Interact',
            self.uid).getHaveMcoinGeneralIds()  #获取有交流记录的武将ID Add by Yew
        data['Scene'] = {
            'BuildingInfo': BuildingInfo,
            'BuyMapInfo': [],
            'InteractGids': interactGids
        }

        #获取武将信息15013 Building_trainUI.GetGenerals()搬过来
        Generals = Gcore.getMod('General', self.uid).getLatestGeneralInfo()
        data['Generals'] = Generals if Generals else []

        #VIP折扣
        data['VipDiscount'] = {
            r['VipLevel']: r['Discount']
            for r in Gcore.getCfg('tb_cfg_vip_up').values()
        }
        data['MaxWorkerNum'] = Gcore.loadCfg(Gcore.defined.CFG_BUILDING).get(
            'MaxWorkerNum', 5)

        #攻城等级
        data['FightLevel'] = Gcore.loadCfg(9301).get('FightLevel')

        #是否首次登录
        data['FirstLogin'] = 0 if data.pop('LoginTimes') else 1

        #军师和指引进度
        data['ArmyAdviserId'] = userProfile.get('ArmyAdviserId', 0)
        data['GuideProcessId'] = userProfile.get('GuideProcessId', 0)

        #进贡百分比
        data['GiveRatio'] = Gcore.loadCfg(1506).get('GiveRatio', 0.05)

        #完成任务数量
        data['MissionFinish'] = Gcore.getMod('Mission',
                                             self.uid).getMissionFinishNum()

        #官网
        data['Website'] = Gcore.loadCoreCfg('Website')

        #心跳时间
        data['HeartBeatInterval'] = Gcore.config.HEARTBEAT_TIME

        #结束-----------------------------------
        runtime = time.time() - startTime
        if Gcore.IsServer:  #调试计时
            row = {
                'UserId': self.uid,
                'OptId': 10001,
                'CallMethod': 'PlayerMod.PlayerInfo',
                'Param': '--skip',
                'Response': '--skip',
                'Runtime': runtime,
                'RecordTime': Gcore.common.datetime(),
            }
            self.db.insert('temp_runtime_log', row, isdelay=True)
        #-------------------------------------
        return data
Example #14
0
 def PlayerInfo(self):
     '''返回获取用户相关资料'''
     startTime = time.time()
         
     fields = ['UserHonour','UserCamp','NickName','VipLevel','BuyMapTimes', 'WorkerNumber',
               'UserIcon','UserExp','UserLevel','Fighter','FightEndTime','ProtectEndTime','BindAccount','LoginTimes',
               'HolderServerId','HolderId','HoldEndTime', #我是否有藩国,藩国结束时间
               ]
     
     userProfile = self.getUserProfile()
     
     data = self.getUserBaseInfo(fields)
     data['UserId'] = self.uid
     data['ServerId'] = Gcore.getServerId() #服务器ID
     data['SuserId']= '%s.%s'%(Gcore.getServerId(),self.uid) #服务器ID跟角色ID组成的标志串
     #data['Worker'] =  self.getUserWorker()
     #@todo 添加更多主角信息
     if Gcore.common.nowtime()>=data['FightEndTime']:
         FightRestTime = 0
     else:
         FightRestTime = data['FightEndTime'] - Gcore.common.nowtime()
     
     data['FightRestTime'] = FightRestTime #被攻打剩余时间   Fighter - 正在被谁攻打
     data.pop('FightEndTime')
     
     buildingCfg = Gcore.loadCfg(CFG_BUILDING)
     data['InitJcoin'] = buildingCfg['InitJcoin']
     data['InitGcoin'] =  buildingCfg['InitGcoin']
     
     data['Coin'] = self.getUserCoin()
     data['ServerTime'] = time.time() #round(time.time(),2)
     data['SoldierLevel'] = Gcore.getMod('Book',self.uid).getTechsLevel(1)
     data['SoldierInfo'] = Gcore.getMod('Building_camp', self.uid).TouchAllSoldiers()
     data['Equipments'] = Gcore.getMod('Equip', self.uid).getAllValidEquip()
     data['Factor'] = { #全部系数
                           'kLeader': Gcore.loadCfg(Gcore.defined.CFG_BATTLE)["kLeaderAddNum"] , #统帅系数 @todo 从配置中读取
                           }
     data['Exchange'] = Gcore.loadCfg( Gcore.defined.CFG_ITEM ).get('exchange') #货币兑换比例
     #data['Timezone'] = Gcore.config.CFG_TIMEZONE #时区
     #data['TimezoneDif'] = Gcore.config.CFG_TIMEZONEDIF #格林时间+CFG_TIMEDIF
     
     data['Timezone'] = Gcore.loadCoreCfg('Timezone') #时区
     data['TimezoneDif'] = int( Gcore.loadCoreCfg('TimezoneDif') ) #格林时间+CFG_TIMEDIF
     
     data['PVPstartTime'] = Gcore.loadCfg( Gcore.defined.CFG_PVP ).get('PVPstartTime') #将弃用
     data['PVPendTime'] = Gcore.loadCfg( Gcore.defined.CFG_PVP ).get('PVPendTime')     #将弃用
     data['PvpTime'] = Gcore.loadCfg( Gcore.defined.CFG_PVP ).get('PvpTime')
     
     #军团信息
     clubInfo = Gcore.getMod('Building_club', self.uid).getMemberInfoByUID(self.uid,['ClubId','DevoteCurrent'])#军团ID 
     data['ClubId'] = clubInfo.get('ClubId',0)
     data['ClubDvo'] = clubInfo.get('DevoteCurrent',0)
     data['ClubBox'] = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost')
     
     #装备传承花费 
     data['DivertCost'] = Gcore.loadCfg(Gcore.defined.CFG_EQUIP).get('DivertCost')
     data['DivertCostType'] = Gcore.loadCfg(Gcore.defined.CFG_EQUIP).get('DivertCostType')
     
     data['Inters'] = Gcore.getMod('Building_home', self.uid).getInters() #内政
     
     #获取场景14001 MapUI.getScene()搬过来的
     BuildingInfo = Gcore.getMod('Building',self.uid).getAllBuildingCoord()
     interactGids=Gcore.getMod('Interact',self.uid).getHaveMcoinGeneralIds()#获取有交流记录的武将ID Add by Yew
     data['Scene'] = {'BuildingInfo':BuildingInfo,'BuyMapInfo':[],'InteractGids':interactGids}
     
     #获取武将信息15013 Building_trainUI.GetGenerals()搬过来
     Generals = Gcore.getMod('General', self.uid).getLatestGeneralInfo()
     data['Generals'] = Generals if Generals else []
     
     #VIP折扣
     data['VipDiscount'] = {r['VipLevel']:r['Discount'] for r in Gcore.getCfg('tb_cfg_vip_up').values()}
     data['MaxWorkerNum'] = Gcore.loadCfg(Gcore.defined.CFG_BUILDING).get('MaxWorkerNum',5)
     
     #攻城等级
     data['FightLevel'] = Gcore.loadCfg(9301).get('FightLevel')
     
     #是否首次登录
     data['FirstLogin'] = 0 if data.pop('LoginTimes') else 1
     
     #军师和指引进度
     data['ArmyAdviserId'] = userProfile.get('ArmyAdviserId',0)
     data['GuideProcessId'] = userProfile.get('GuideProcessId',0)
     
     #进贡百分比
     data['GiveRatio'] = Gcore.loadCfg(1506).get('GiveRatio',0.05)
     
     #完成任务数量
     data['MissionFinish'] = Gcore.getMod('Mission',self.uid).getMissionFinishNum()
     
     #官网
     data['Website'] = Gcore.loadCoreCfg('Website')
     
     #心跳时间
     data['HeartBeatInterval'] = Gcore.config.HEARTBEAT_TIME
     
     
     #结束-----------------------------------
     runtime = time.time() - startTime
     if Gcore.IsServer: #调试计时
         row = {
                  'UserId':self.uid,
                  'OptId':10001,
                  'CallMethod':'PlayerMod.PlayerInfo',
                  'Param':'--skip',
                  'Response':'--skip',
                  'Runtime':runtime,
                  'RecordTime':Gcore.common.datetime(),
                  }
         self.db.insert('temp_runtime_log', row, isdelay=True)
     #-------------------------------------
     return data
Example #15
0
            j += ' END '
            g += ' END '
            sql = 'UPDATE %s SET JcoinGive=JcoinGive+%s, GcoinGive=GcoinGive+%s, LastCollectTime=%d WHERE %s' % (
                table, j, g, int(curtime), where)
            print '进贡记录:', sql
            db.execute(sql)

        #总服redis
        redis_client = Gcore.redisM
        holds = redis_client.hgetall('sgHold')
        #print 'holds', holds
        for giver in holds:
            #print 'giver is', giver
            try:
                sid, uid = map(int, giver.split('.'))
                if sid != Gcore.getServerId():  #奴隶不是本服的
                    continue
                v_fields = map(int, holds[giver].split('.'))
                #print 'fields', fields
                if v_fields[0] == Gcore.getServerId():
                    continue

                endtime, lastcollecttime = v_fields[4:]
                seconds = int(min(endtime, curtime) - lastcollecttime)
                jc = int(seconds * (Speed.get(uid, {}).get(1, 0) / 3600.))
                gc = int(seconds * (Speed.get(uid, {}).get(2, 0) / 3600.))
                print 'jc', jc, 'gc', gc

                incdic[uid] = {1: jc, 2: gc}

                v = '.'.join(map(str, v_fields[0:5] + [int(curtime)]))
Example #16
0
 def _getOpponentSample(self):
     '''根据规则获取 我的对手'''
     import random
     row = self._getRank()
     RankId = row['RankId']
     MaxRankId = self.db.out_field('tb_rank_fight','Max(RankId)')
     
     if RankId>1000:
         pop = 200
     elif 1000>=RankId>500:
         pop = 100
     elif 500>=RankId>200:
         pop = 50
     elif 200>=RankId>3:
         pop = 10
     elif 3>=RankId>0:
         pop = 3
     
     uplimit = RankId-pop if RankId-pop>1 else 1 #最前是第1名
     downlimit = MaxRankId if  MaxRankId < RankId + 10 else RankId + 10 
     downSelectNum = 5 if downlimit - RankId >= 5 else downlimit - RankId #正常是2 包尾除外
     upSelectNum = 5 if RankId - uplimit >= 5 else RankId - uplimit #正常是3 前列除外
     
     downSample = random.sample(xrange(RankId+1,downlimit+1),downSelectNum)
     upSample = random.sample(xrange(uplimit,RankId),upSelectNum)
     if 0:
         print '*'*40
         print '我的排名',RankId
         print '取多少名之内 pop',pop
         print '取名上限 uplimit',uplimit
         print '取名下限 downlimit',downlimit
         print '往下取 downSelectNum',downSelectNum
         print '往上取 upSelectNum',upSelectNum
         
         print '取出的后面人 downSample',downSample
         print '取出的前面人 upSample',upSample
     
     targetSample = []
     if len(upSample)<3:
         targetSample += upSample
         downSelectNum = min([downSelectNum, 5 - len(upSample)])
         targetSample += random.sample(downSample,downSelectNum)
     elif len(downSample)<2:
         targetSample += downSample
         upSelectNum = min([upSelectNum, 5 - len(downSample)])
         targetSample += random.sample(upSample,upSelectNum)
     else:
         targetSample += random.sample(downSample,2)
         targetSample += random.sample(upSample,3)
     
     OpponentSample = []
     if targetSample:
         targetSample.sort(reverse=True)
         where = 'UserId<>%s AND '%self.uid
         where += self.db.inWhere('RankId',targetSample)
         sql = 'SELECT tb_user.*,tb_rank_fight.RankId FROM tb_user INNER JOIN tb_rank_fight ON tb_user.UserId=tb_rank_fight.UserId WHERE %s ORDER BY RankId'%where
         rows = self.db.fetchall(sql)
         
         for row in rows:
             d = {
                  'UserId':row['UserId'],
                  'UserLevel':row['UserLevel'],
                  'NickName':row['NickName'],
                  'UserIcon':row['UserIcon'],
                  'RankId':row['RankId'],
                  'ServerId':Gcore.getServerId(),
                  }
             OpponentSample.append(d)
     OpponentSample = common.list2dict(OpponentSample)
     
     return OpponentSample
Example #17
0
    def _getOpponentSample(self):
        '''根据规则获取 我的对手'''
        import random
        row = self._getRank()
        RankId = row['RankId']
        MaxRankId = self.db.out_field('tb_rank_fight', 'Max(RankId)')

        if RankId > 1000:
            pop = 200
        elif 1000 >= RankId > 500:
            pop = 100
        elif 500 >= RankId > 200:
            pop = 50
        elif 200 >= RankId > 3:
            pop = 10
        elif 3 >= RankId > 0:
            pop = 3

        uplimit = RankId - pop if RankId - pop > 1 else 1  #最前是第1名
        downlimit = MaxRankId if MaxRankId < RankId + 10 else RankId + 10
        downSelectNum = 5 if downlimit - RankId >= 5 else downlimit - RankId  #正常是2 包尾除外
        upSelectNum = 5 if RankId - uplimit >= 5 else RankId - uplimit  #正常是3 前列除外

        downSample = random.sample(xrange(RankId + 1, downlimit + 1),
                                   downSelectNum)
        upSample = random.sample(xrange(uplimit, RankId), upSelectNum)
        if 0:
            print '*' * 40
            print '我的排名', RankId
            print '取多少名之内 pop', pop
            print '取名上限 uplimit', uplimit
            print '取名下限 downlimit', downlimit
            print '往下取 downSelectNum', downSelectNum
            print '往上取 upSelectNum', upSelectNum

            print '取出的后面人 downSample', downSample
            print '取出的前面人 upSample', upSample

        targetSample = []
        if len(upSample) < 3:
            targetSample += upSample
            downSelectNum = min([downSelectNum, 5 - len(upSample)])
            targetSample += random.sample(downSample, downSelectNum)
        elif len(downSample) < 2:
            targetSample += downSample
            upSelectNum = min([upSelectNum, 5 - len(downSample)])
            targetSample += random.sample(upSample, upSelectNum)
        else:
            targetSample += random.sample(downSample, 2)
            targetSample += random.sample(upSample, 3)

        OpponentSample = []
        if targetSample:
            targetSample.sort(reverse=True)
            where = 'UserId<>%s AND ' % self.uid
            where += self.db.inWhere('RankId', targetSample)
            sql = 'SELECT tb_user.*,tb_rank_fight.RankId FROM tb_user INNER JOIN tb_rank_fight ON tb_user.UserId=tb_rank_fight.UserId WHERE %s ORDER BY RankId' % where
            rows = self.db.fetchall(sql)

            for row in rows:
                d = {
                    'UserId': row['UserId'],
                    'UserLevel': row['UserLevel'],
                    'NickName': row['NickName'],
                    'UserIcon': row['UserIcon'],
                    'RankId': row['RankId'],
                    'ServerId': Gcore.getServerId(),
                }
                OpponentSample.append(d)
        OpponentSample = common.list2dict(OpponentSample)

        return OpponentSample
Example #18
0
        # 返回值:-2 反抗次数已达到最大 -1 参数错误  0 没达到成功条件 1达到成功条件
        if not 0 <= process <= 1:
            return -1  # 攻城进度取值范围不对
        TimeStamp = TimeStamp if TimeStamp else time.time()
        cnt, pro = self.calcRevent(TimeStamp)
        ratio = 0.5  # 读配置
        maxnum = 5  # 读配置

        cnt_new = cnt + 1
        pro_new = pro + float(ratio * process)  # 取攻城进度的50%。
        if cnt_new > maxnum:
            return -2
        elif pro_new >= 1.0 or flag == 1:  # 累积进度达到100% ## 读配置
            self.db.execute('DELETE FROM `tb_hold_revenge` WHERE UserId="%s"' % self.uid)
            return 1
        else:  # 增加累计进度
            arr = {}
            arr["ProcessTotal"] = pro_new
            arr["RevengeCount"] = cnt_new
            arr["LastRevengeDate"] = datetime.date.strftime(datetime.date.fromtimestamp(TimeStamp), "%Y-%m-%d")
            self.db.update("tb_hold_revenge", arr, 'UserId="%s"' % self.uid)


# end class Building_holdMod

if "__main__" == __name__:
    uid = 1006
    c = Building_holdMod(uid)
    # print c.setReventProcess(0.36)
    print type(Gcore.getServerId())
Example #19
0
 def __init__(self, uid ,ServerId=None):
     '''@para: ServerId 测试用'''
     self.uid = uid
     self.serverid = ServerId if ServerId else Gcore.getServerId()
     self.encode = Gcore.common.json_encode
     Base.__init__(self, uid)
Example #20
0
            return -1  #攻城进度取值范围不对
        TimeStamp = TimeStamp if TimeStamp else time.time()
        cnt, pro = self.calcRevent(TimeStamp)
        ratio = 0.5  #读配置
        maxnum = 5  #读配置

        cnt_new = cnt + 1
        pro_new = pro + float(ratio * process)  #取攻城进度的50%。
        if cnt_new > maxnum:
            return -2
        elif pro_new >= 1.0 or flag == 1:  #累积进度达到100% ## 读配置
            self.db.execute('DELETE FROM `tb_hold_revenge` WHERE UserId="%s"' %
                            self.uid)
            return 1
        else:  #增加累计进度
            arr = {}
            arr['ProcessTotal'] = pro_new
            arr['RevengeCount'] = cnt_new
            arr['LastRevengeDate'] = datetime.date.strftime(
                datetime.date.fromtimestamp(TimeStamp), '%Y-%m-%d')
            self.db.update('tb_hold_revenge', arr, 'UserId="%s"' % self.uid)


#end class Building_holdMod

if '__main__' == __name__:
    uid = 1006
    c = Building_holdMod(uid)
    #print c.setReventProcess(0.36)
    print type(Gcore.getServerId())
Example #21
0
 def __init__(self, uid):
     Base.__init__(self, uid)
     self.uid = uid
     self.serverid = int(Gcore.getServerId())
Example #22
0
 def __init__(self, uid):
     Base.__init__(self, uid)
     self.uid = uid
     self.serverid = int(Gcore.getServerId())
Example #23
0
                j += ' WHEN %d THEN %d ' % (lst[0], lst[1])
                g += ' WHEN %d THEN %d ' % (lst[0], lst[2])
            j += ' END '; g += ' END '
            sql = 'UPDATE %s SET JcoinGive=JcoinGive+%s, GcoinGive=GcoinGive+%s, LastCollectTime=%d WHERE %s' % (table, j, g, int(curtime), where)
            print '进贡记录:',sql
            db.execute(sql)
        
        #总服redis
        redis_client = Gcore.redisM
        holds = redis_client.hgetall('sgHold')
        #print 'holds', holds
        for giver in holds:
            #print 'giver is', giver
            try:
                sid, uid = map(int, giver.split('.'))
                if sid != Gcore.getServerId(): #奴隶不是本服的
                    continue
                v_fields = map(int, holds[giver].split('.'))
                #print 'fields', fields
                if v_fields[0] == Gcore.getServerId():
                    continue
                
                endtime, lastcollecttime = v_fields[4:]
                seconds = int(min(endtime, curtime) - lastcollecttime)
                jc = int(seconds*(Speed.get(uid, {}).get(1, 0) / 3600.))
                gc = int(seconds*(Speed.get(uid, {}).get(2, 0) / 3600.))
                print 'jc', jc, 'gc',gc

                incdic[uid]={1:jc,2:gc}

                v = '.'.join(map(str, v_fields[0:5] + [int(curtime)]))