Example #1
0
 def test(self,p={}):
     '''测试获取当前缓存的用户信息'''
     optId = 99001
     Gcore.getUserData(1001, 'UserLevel')
     body = { 'Gcore.StorageUser': str(Gcore.StorageUser) }
     print 'body',body
     return Gcore.out(optId,body)
Example #2
0
 def test(self, p={}):
     '''测试获取当前缓存的用户信息'''
     optId = 99001
     Gcore.getUserData(1001, 'UserLevel')
     body = {'Gcore.StorageUser': str(Gcore.StorageUser)}
     print 'body', body
     return Gcore.out(optId, body)
Example #3
0
    def login(self,loginIp=None,loginMode=None):
        '''登入时调用的方法'''
        now = time.time()
        sql = "UPDATE tb_user SET LastLoginTime=UNIX_TIMESTAMP(),Online=1,LoginTimes=LoginTimes+1 WHERE UserId=%s"%self.uid
        self.db.execute(sql)
        
        #if not self.uid in Gcore.StorageUser: #缓存基础用户信息
        if 1: # fixed by zhoujingjiang
            self.cacheUserData(self.uid)

        UserType = Gcore.getUserData(self.uid,'UserType')   
        #添加登录日志
#         loginLogTB = 'tb_log_login201306'
        loginLogTB = self.tb_log_login()
        data = {'UserId':self.uid,'LoginTime':now,'UserType':UserType,
                'LoginModel':loginMode,'LoginIP':loginIp}
        self.logId = self.db.insert(loginLogTB,data)
        print self.uid,'login get logId:%s at %s'%(self.logId,now)
        
        key = Gcore.redisKey(self.uid)
        Gcore.redisM.hset('sgLogin',key,'1')
        UserLevel = self.getUserLevel()
        modActivity=Gcore.getMod('Activity',self.uid)
        modActivity.signin(0,'')
        if UserLevel>=Gcore.loadCfg(9301).get('FightLevel'):
            row = {}
            row['Online']=1 
            row['UserId']=self.uid
Example #4
0
 def gainDeveote(self,clubId,gainWay,**p):
     '''
     :获得贡献
     @param clubId:
     @param gainWay:获得方式 1贡献 3抽奖
     @param p:if gainWay==1: p{coinValue,coinType}
              elif gainWay==3: p{devoteNum}
     '''
     if not clubId:
         return 0
     
     devoteNum = p.get('devoteNum',0)
     record = {'ClubId':clubId,'UserId':self.uid,
               'UserType':Gcore.getUserData(self.uid,'UserType'),
               'ActionType':gainWay,'DevoteNum':devoteNum,
               'CreateTime':time.time()}
     if gainWay==1:#贡献获得
         coinType = p['coinType']
         coinValue = p['coinValue']
         devoteBase = Gcore.loadCfg(defined.CFG_BUILDING_CLUB).get('ClubGiveBase').get( str(coinType))
         devoteNum = coinValue/devoteBase
         record['DevoteNum'] = devoteNum
         record['DevoteCoinType'] = coinType
         record['DevoteCoinValue'] = coinValue
     sql = 'UPDATE tb_club_member \
             SET  DevoteCurrent=DevoteCurrent+%s,\
                  DevoteTotal=DevoteTotal+%s \
             WHERE UserId=%s AND ClubId=%s'%(devoteNum,devoteNum,self.uid,clubId)
     if self.db.execute(sql):
         self.db.insert('tb_log_club_devote',record)
         return devoteNum
     else:
         0
Example #5
0
    def login(self, loginIp=None, loginMode=None):
        '''登入时调用的方法'''
        now = time.time()
        sql = "UPDATE tb_user SET LastLoginTime=UNIX_TIMESTAMP(),Online=1,LoginTimes=LoginTimes+1 WHERE UserId=%s" % self.uid
        self.db.execute(sql)

        #if not self.uid in Gcore.StorageUser: #缓存基础用户信息
        if 1:  # fixed by zhoujingjiang
            self.cacheUserData(self.uid)

        UserType = Gcore.getUserData(self.uid, 'UserType')
        #添加登录日志
        #         loginLogTB = 'tb_log_login201306'
        loginLogTB = self.tb_log_login()
        data = {
            'UserId': self.uid,
            'LoginTime': now,
            'UserType': UserType,
            'LoginModel': loginMode,
            'LoginIP': loginIp
        }
        self.logId = self.db.insert(loginLogTB, data)
        print self.uid, 'login get logId:%s at %s' % (self.logId, now)

        key = Gcore.redisKey(self.uid)
        Gcore.redisM.hset('sgLogin', key, '1')
        UserLevel = self.getUserLevel()
        modActivity = Gcore.getMod('Activity', self.uid)
        modActivity.signin(0, '')
        if UserLevel >= Gcore.loadCfg(9301).get('FightLevel'):
            row = {}
            row['Online'] = 1
            row['UserId'] = self.uid
Example #6
0
 def addUserExp(self,getWay,amount=0,optId=0):
     '''
     :增加主角经验(动作触发)
     @param getWay: 用户获得经验方式0:直接加经验,1-99:消耗加经验 101-199: 事件加经验
     @param amount: if getWay==0:amount='增加的经验值';elif 1<1getWay<99:amount='消耗货币量';
     @return: 返回主角经验等级,当前经验
     '''
     
     expCfg = Gcore.getCfg('tb_cfg_exp_get',getWay)
     fields = ['UserLevel','UserExp']
     userInfo = self.db.out_fields('tb_user',fields,'UserId=%s'%self.uid)
     userLevel = userInfo['UserLevel']
     userExp = userInfo['UserExp']
     getExp = 0
       
     if expCfg:#动作增加经验方式
         segment = getWay/100#判断是消耗还是事件      
         if segment==0:#消耗
             factor1 = expCfg.get('Factor1',0)
             factor2 = expCfg.get('Factor2',0)
             getExp = int(factor1*amount+factor2*userLevel)
             
         elif segment==1 and self._getLimitOfEvent(getWay):#事件
             baseExp = expCfg.get('BaseExp',0)
             getExp = int(baseExp*(userLevel+1)*(1+userLevel/200.0)+1)
             
     elif getWay==0:#直接加经验
         getExp=amount
     
     #增加经验,同时更新等级
     if getExp>0:
         updateExp = self._calUserLevel(userLevel, userExp+getExp)
         self.db.update('tb_user',updateExp,'UserId=%s'%self.uid)
         newLevel = updateExp.get('UserLevel')
         
         #获得经验记录
         logData = {'UserId':self.uid,'GetWay':getWay,'OptId':optId,
                    'UserType':Gcore.getUserData(self.uid,'UserType'),
                    'UserLevel':newLevel,'ExpValue':getExp,'CreateTime':time.time()}
         self.db.insert('tb_log_exp',logData,isdelay=True)
         
         #主角升级
         if newLevel>userLevel:
             #升级推送
             Gcore.push(108,self.uid,{'UserLevel':newLevel})
             mMod = Gcore.getMod('Mission',self.uid)
             mMod.getNewMission(userLevel=newLevel)#用户升级查看有没有新任务
             Gcore.setUserData(self.uid, {'UserLevel':newLevel}) #更新缓存中的用户等级  Lizr
             Gcore.getMod('General',self.uid).touchGeneralLv(newLevel)
             Gcore.getMod('War',self.uid).touchActPoint(userLevel,newLevel) #更新行动力
             modActivity=Gcore.getMod('Activity',self.uid)#报错
             modActivity.growUpAward(newLevel, userLevel)#成长奖励活动Yew
             if newLevel >= Gcore.loadCfg(Gcore.defined.CFG_RANK_FIGHT).get('RankFightOpenLevel',20):
                 Gcore.getMod('RankFight',self.uid).joinRankFight() #每次升级都尝试加入排行榜 防止有漏
                 
         return updateExp
     else:
         return userInfo   
Example #7
0
 def RankFightInfo(self,para={}):
     '''比武主界面 和 排名奖励界面 所需数据'''
     optId = 24001
     UserLevel = Gcore.getUserData(self.uid,'UserLevel')
     OpenLevel = Gcore.loadCfg(2401).get('RankFightOpenLevel')
     if UserLevel<OpenLevel:
         return Gcore.error(optId,-24001001)
     RankFightInfo = self.mod.getRankFightInfo()
     RankReward = self.mod.getRankReward()
     return Gcore.out(optId,{'RankFightInfo':RankFightInfo,'RankReward':RankReward})
Example #8
0
 def insertBoxLog(self,clubId,boxType,data):
     '''
      :插入宝箱开奖记录
      @param data:宝箱数据
     '''
     logData = {'ClubId':clubId,'UserId':self.uid,
                'UserType':Gcore.getUserData(self.uid,'UserType'),
                'BoxType':boxType,'RewardType':data['RewardType'],
                'GoodsId':data['GoodsId'],'GoodsNum':data['GoodsNum'],
                'CreateTime':time.time()}
     return self.db.insert('tb_log_club_box',logData)
Example #9
0
 def addTrainRecord(self,gt,tt):
     '''
     :武将训练记录
     @param gt:武将类型
     @param tt:训练类型
     #By Zhanggh 2013-5-29
     '''
     data = {'UserId':self.uid,'GeneralType':gt,
             'UserType':Gcore.getUserData(self.uid,'UserType'),
             'TrainType':tt,'CreateTime':time.time()}
     self.db.insert('tb_log_general_train',data,isdelay=True)
Example #10
0
 def _getMissionCache(self,action=''):
     '''获取任务缓存'''
     activeMission = Gcore.getUserData(self.uid,'ActiveMission')#缓存查询
     if (activeMission is None) or (not isinstance(activeMission,dict)):
         myLog = Gcore.getLogger('zhanggh','mission')
         myLog.error("任务缓存有异常,UserId:%s,动作:%s,用户缓存内容:"%(self.uid,action))
         myLog.error( Gcore.StorageUser.get(self.uid))
         
         activeMission = self.db.out_rows('tb_mission',['MissionId','GetValue'],'UserId=%s AND Status in (1,2)'%self.uid)
         activeMission = {k['MissionId']:k for k in activeMission}
         Gcore.setUserData(self.uid,{'ActiveMission':activeMission})
     return activeMission
Example #11
0
 def _getAchieveCache(self,action=''):
     '''获取成就缓存'''
     activeAchieve = Gcore.getUserData(self.uid, 'ActiveAchieve')#缓存活跃成就
     if (activeAchieve is None) or (not isinstance(activeAchieve,list or tuple)):
         myLog = Gcore.getLogger('zhanggh','achieve')
         myLog.error("成就缓存有异常,UserId:%s,动作:%s,用户缓存内容:"%(self.uid,action))
         myLog.error( Gcore.StorageUser.get(self.uid))
         
         activeAchieve = self.getAchievements()
         activeAchieve = [k for k in activeAchieve if activeAchieve[k]['Finished']==0]
         Gcore.setUserData(self.uid,{'ActiveAchieve':activeAchieve})
     return activeAchieve
Example #12
0
    def warSweepNew(self, warId, SweepTimes):
        '''扫荡'''
        result = {}
        UserData = self.getUserInfo(['ProcessWarId'])
        ProcessWarId = UserData['ProcessWarId']

        rowStar = self.db.out_fields('tb_war_star', '*',
                                     'UserId=%s' % self.uid)
        RestPoint, MaxPoint = self.getActPoint()
        if warId > ProcessWarId or not rowStar.get('War%s' % warId):
            return False

        if RestPoint < Gcore.getCfg('tb_cfg_pve', warId,
                                    'ActPointNeed') * SweepTimes:
            return False
        else:
            Gcore.setUserData(self.uid, {'Sweeping': True})

            #@todo 自动补兵
            for i in xrange(SweepTimes):
                restTimes = SweepTimes - i - 1
                if not Gcore.getUserData(self.uid, 'Sweeping'):  #用户落线也会停止
                    break
                else:
                    gevent.sleep(
                        Gcore.loadCfg(9101).get('SweepSleep'))  #每场间隔3秒 读配置

                modBattle = Gcore.getMod('Battle', self.uid, True)
                initWarResult = modBattle.initWar(warId, 1)  #定义为扫荡战役
                if not initWarResult:
                    print '初始化战斗失败'
                    break
                modBattle.getWarInfo()
                re = modBattle.endBattle({"resultType": 5})
                #print '战斗结果',re
                result[warId] = re  #结构不能更改 需要和前台一样
                self.warlog(WarId=warId,
                            IsWarSweep=1,
                            Result=re.get('Result', 0))  #@todo 添加更完整战役结果

                Gcore.push(
                    111, self.uid, {
                        'result': result,
                        'restPoint': RestPoint,
                        'restTimes': restTimes
                    })
                if not re.get('Result'):
                    break
                else:
                    RestPoint -= 1

            return True
Example #13
0
 def makeRankLog(self,OpUserId,FightResult,MyRankId):
     '''制造日志
     OpUserId: 对手用户ID
     FightResult : 战斗结果
     MyRankId: 我的排名
     OpRankId: 对方的排名
     '''
     if FightResult:
         ToRankId = self.db.out_field('tb_rank_fight','RankId','UserId=%s'%self.uid)
     else:
         ToRankId = MyRankId
     d = {
          'UserId':self.uid,
          'NickName':Gcore.getUserData(self.uid,'NickName'),
          'OpUserId':OpUserId,
          'OpNickName':Gcore.getUserData(OpUserId,'NickName'),
          'FightResult':FightResult,
          'FromRankId':MyRankId,
          'ToRankId':ToRankId,
          'CreateTime':Gcore.common.nowtime(),
          }
         
     self.db.insert('tb_rank_fight_log',d)
Example #14
0
    def makeRankLog(self, OpUserId, FightResult, MyRankId):
        '''制造日志
        OpUserId: 对手用户ID
        FightResult : 战斗结果
        MyRankId: 我的排名
        OpRankId: 对方的排名
        '''
        if FightResult:
            ToRankId = self.db.out_field('tb_rank_fight', 'RankId',
                                         'UserId=%s' % self.uid)
        else:
            ToRankId = MyRankId
        d = {
            'UserId': self.uid,
            'NickName': Gcore.getUserData(self.uid, 'NickName'),
            'OpUserId': OpUserId,
            'OpNickName': Gcore.getUserData(OpUserId, 'NickName'),
            'FightResult': FightResult,
            'FromRankId': MyRankId,
            'ToRankId': ToRankId,
            'CreateTime': Gcore.common.nowtime(),
        }

        self.db.insert('tb_rank_fight_log', d)
Example #15
0
    def gainHonour(self, honourValue, optId=0):
        '''获得荣誉  Lizr 
        @param honourValue:荣誉值 +增加,-消耗
        @param optId:功能号 
        @author: zhanggh 6.4
        @return: 增加或消耗的荣誉
        '''
        userInfo = self.db.out_fields('tb_user', ['UserHonour', 'UserLevel'],
                                      'UserId=%s' % self.uid)
        curHonour = userInfo['UserHonour']
        actionType = 1
        updateVal = curHonour + honourValue

        if honourValue < 0:  #消耗荣誉
            actionType = 2
            if curHonour <= 0:
                return 0
            if updateVal < 0:
                updateVal = 0
                honourValue = -curHonour

        #更新荣誉
        self.db.update('tb_user', {'UserHonour': updateVal},
                       'UserId=%s' % self.uid)

        #记录荣誉获得
        record = {
            'UserId': self.uid,
            'UserLevel': userInfo['UserLevel'],
            'UserType': Gcore.getUserData(self.uid, 'UserType'),
            'Action': actionType,
            'HonourNumber': abs(honourValue),
            'OptId': optId,
            'NowHonour': updateVal,
            'CreateTime': time.time()
        }
        self.db.insert('tb_log_honour', record, isdelay=True)

        #记录成就
        if actionType == 1:
            recordData = {'ValType': 0, 'Val': honourValue}
            Gcore.getMod('Building_home',
                         self.uid).achieveTrigger(5, recordData)
            Gcore.getMod('Mission', self.uid).missionTrigger(5, recordData)

        return honourValue
Example #16
0
 def insertItemLog(self, optId, itemId, itemNum, action):
     '''
     @param optId:
     @param itemId:
     @param itemNum:
     @param action:1为产出,2为消耗
     '''
     now = Gcore.common.nowtime()
     row = {'UserId': self.uid,
          'UserType': Gcore.getUserData(self.uid,'UserType'),
          'Action': action,
          'ItemId': itemId,
          'Num': itemNum,
          'OptId': optId,
          'CreateTime': now
     }
     self.db.insert('tb_log_item', row, isdelay = False)
Example #17
0
 def _GetNextPay(self,AltarType,TimeStamp):
     AltarConfig = Gcore.loadCfg(CFG_BUILDING_ALTAR)  
     AlreadyLotteryCnt = self.GetLotteryCnt({'AltarType':AltarType, 'ClientTime':TimeStamp})
     AlreadyLotteryCnt = AlreadyLotteryCnt.get('body', {}).get('LotteryCount', -1)
     if AltarType==2:
         NextCostType = AltarConfig['LandCoinType']
         NextCost = AltarConfig['LandTimesCost']
     else:
         NextCostType = AltarConfig['SkyCoinType']
         NextCost = min(AltarConfig['SkyTimesCost'] * (AlreadyLotteryCnt + 1),50)
         #打折
         vipLevel = Gcore.getUserData(self.uid, 'VipLevel')
         discount = Gcore.getCfg('tb_cfg_vip_up',vipLevel,'Discount')
         discount = discount if discount else 1
         NextCost = math.ceil(NextCost*discount)
     
     NextLoterryPay={'NextCostType':NextCostType,'NextCost':NextCost}
     return NextLoterryPay
Example #18
0
 def insertItemLog(self, optId, itemId, itemNum, action):
     '''
     @param optId:
     @param itemId:
     @param itemNum:
     @param action:1为产出,2为消耗
     '''
     now = Gcore.common.nowtime()
     row = {
         'UserId': self.uid,
         'UserType': Gcore.getUserData(self.uid, 'UserType'),
         'Action': action,
         'ItemId': itemId,
         'Num': itemNum,
         'OptId': optId,
         'CreateTime': now
     }
     self.db.insert('tb_log_item', row, isdelay=False)
Example #19
0
 def _getRank(self,UserId=None):
     '''获取我的排名记录相关信息,一条'''
     if not UserId:
         UserId = self.uid
     row =  self.db.out_fields('tb_rank_fight','*','UserId=%s'%UserId)
     
     #-------------- 特殊情况处理:超过等级 但未入排名 -------------
     if not row:
         UserLevel = Gcore.getUserData(UserId,'UserLevel')
         OpenLevel = Gcore.loadCfg(2401).get('RankFightOpenLevel')
         if UserLevel >= OpenLevel:
             self.db.insert('tb_rank_fight',{'UserId':UserId})
         row =  self.db.out_fields('tb_rank_fight','*','UserId=%s'%UserId)
     #----------------------------------------------------------
          
     if row['LastFightTime'] < common.today0time(): #上一次是昨天
         row['TodayFightTimes'] = 0
     
     return row
Example #20
0
    def warSweepNew(self,warId,SweepTimes):
        '''扫荡'''
        result = {}
        UserData = self.getUserInfo(['ProcessWarId'])
        ProcessWarId = UserData['ProcessWarId']
        
        rowStar = self.db.out_fields('tb_war_star','*','UserId=%s'%self.uid)
        RestPoint,MaxPoint = self.getActPoint()
        if warId>ProcessWarId or not rowStar.get('War%s'%warId):
            return False
              
        if RestPoint< Gcore.getCfg('tb_cfg_pve',warId,'ActPointNeed')*SweepTimes:
            return False
        else:
            Gcore.setUserData(self.uid, {'Sweeping':True} )
            
            #@todo 自动补兵
            for i in xrange(SweepTimes):
                restTimes = SweepTimes-i-1
                if not Gcore.getUserData(self.uid, 'Sweeping'): #用户落线也会停止
                    break
                else:
                    gevent.sleep( Gcore.loadCfg(9101).get('SweepSleep') ) #每场间隔3秒 读配置
                    
                modBattle = Gcore.getMod('Battle',self.uid,True)
                initWarResult = modBattle.initWar(warId,1) #定义为扫荡战役
                if not initWarResult:
                    print '初始化战斗失败'
                    break
                modBattle.getWarInfo()
                re = modBattle.endBattle({"resultType":5})
                #print '战斗结果',re
                result[warId] = re #结构不能更改 需要和前台一样
                self.warlog(WarId=warId,IsWarSweep=1,Result=re.get('Result',0)) #@todo 添加更完整战役结果
                
                Gcore.push(111,self.uid,{'result':result,'restPoint':RestPoint,'restTimes':restTimes})
                if not re.get('Result'):
                    break
                else:
                    RestPoint-=1

            return True  
Example #21
0
    def _getRank(self, UserId=None):
        '''获取我的排名记录相关信息,一条'''
        if not UserId:
            UserId = self.uid
        row = self.db.out_fields('tb_rank_fight', '*', 'UserId=%s' % UserId)

        #-------------- 特殊情况处理:超过等级 但未入排名 -------------
        if not row:
            UserLevel = Gcore.getUserData(UserId, 'UserLevel')
            OpenLevel = Gcore.loadCfg(2401).get('RankFightOpenLevel')
            if UserLevel >= OpenLevel:
                self.db.insert('tb_rank_fight', {'UserId': UserId})
            row = self.db.out_fields('tb_rank_fight', '*',
                                     'UserId=%s' % UserId)
        #----------------------------------------------------------

        if row['LastFightTime'] < common.today0time():  #上一次是昨天
            row['TodayFightTimes'] = 0

        return row
Example #22
0
    def updateMissions(self,mData):
        '''更新多个任务(更新相应的任务缓存数据)
        @param mData: {MId:updateData} MId:任务ID,updateData:更新内容
        @return: 更新数目
        '''
        tb_m = 'tb_mission'
        mCfg = Gcore.getCfg('tb_cfg_mission')
        activeMission = Gcore.getUserData(self.uid, 'ActiveMission')
        
#         print '更新任务信息=>',mData
#         print '任务缓存信息=>',activeMission
        
        pusMId = []
        updateNum = 0
        for mId in mData:
            data = mData[mId]
            getVal = data.get('GetValue',0)
            paramB = mCfg[mId]['ParamB']
            
            #如果任务完成推送消息
            if getVal>=paramB:
                data['GetValue']=paramB
                data['Status']=3
                data['CompleteTime'] = time.time()
                pusMId.append(mId)
                activeMission.pop(mId,None)#任务完成删除缓存任务
                
            elif getVal:
                activeMission[mId]['GetValue'] = getVal#更新缓存任务信息
            
            if self.db.update(tb_m,data,'UserId=%s AND MissionId=%s'%(self.uid,mId)):
                updateNum +=1
       
        #更新任务缓存
        Gcore.setUserData(self.uid, {'ActiveMission':activeMission})
        #推送通知任务完成
        if pusMId:
            print '任务完成',str(pusMId)
            Gcore.push(102,self.uid,{'MT':2,'MIDS':pusMId})
        return updateNum
Example #23
0
    def payDevote(self,clubId,num):
        '''
        :支付贡献点
        @param num:贡献点
        @return: 支付成功返回余额,-1:支付失败,-2:贡献点不足
        '''
        if clubId is None:
            return -1#支付失败
        current = self.db.out_field('tb_club_member','DevoteCurrent','UserId=%s AND ClubId=%s'%(self.uid,clubId))

        left = current-num
        if left<0:
            return -2#贡献点不足
        flag = self.db.update('tb_club_member',{'DevoteCurrent':left},'UserId=%s AND ClubId=%s'%(self.uid,clubId))
        if not flag:
            return -1#支付失败
        record = {'ClubId':clubId,'UserId':self.uid,
                  'UserType':Gcore.getUserData(self.uid,'UserType'),
                  'ActionType':2,'DevoteNum':num,
                  'CreateTime':time.time()}
        self.db.insert('tb_log_club_devote',record)
        return left
Example #24
0
    def addNewGeneral(self, GeneralType, BuildingId, TimeStamp, GeneralState=2, flag=False, getWay=1):
        '''增加新武将'''
        # 参数
        # + BuildingId - 放武将的点将台ID
        # + GeneralType - 武将类型
        # + flag - 是否需要检查该类型的武将是否已存在
        # + getWay - 武将的获得方式

        GeneralCfg = Gcore.getCfg('tb_cfg_general', GeneralType)       
        
        if (flag and int(GeneralType) in self.getGeneralTypeList()) or not GeneralCfg:
            return False

        setClause = \
        {
         "UserId":self.uid,
         "GeneralType":GeneralType,
         "GeneralLevel":1,
         "TrainForceValue":0,
         "TrainWitValue":0,
         "TrainSpeedValue":0, 
         "TrainLeaderValue":0,
         "ForceValue":GeneralCfg.get('BaseForce'),
         "WitValue":GeneralCfg.get('BaseWit'),
         "SpeedValue":GeneralCfg.get('BaseSpeed'),
         "LeaderValue":GeneralCfg.get('BaseLeader'),
         "ExpValue":0,
         "Location":BuildingId,
         "GeneralState":GeneralState,
         "CreateTime":TimeStamp
        }
        stat = self.db.insert(self.tb_general(), setClause)
        
        if stat: #added by zhangguanghui
            logData = {'UserId':self.uid,'GeneralType':GeneralType,
                       'UserType':Gcore.getUserData(self.uid,'UserType'),
                       'GetWay':getWay,'CreateTime':time.time()}
            self.db.insert('tb_log_general', logData, isdelay=True)
        return stat
Example #25
0
 def gainHonour(self,honourValue,optId=0):
     '''获得荣誉  Lizr 
     @param honourValue:荣誉值 +增加,-消耗
     @param optId:功能号 
     @author: zhanggh 6.4
     @return: 增加或消耗的荣誉
     '''
     userInfo = self.db.out_fields('tb_user',['UserHonour','UserLevel'],'UserId=%s'%self.uid)
     curHonour = userInfo['UserHonour']
     actionType = 1
     updateVal = curHonour+honourValue
     
     if honourValue<0:#消耗荣誉
         actionType = 2
         if curHonour <= 0:
             return 0
         if updateVal<0:
             updateVal = 0
             honourValue = -curHonour
     
     #更新荣誉
     self.db.update('tb_user',{'UserHonour':updateVal},'UserId=%s'%self.uid)
     
     #记录荣誉获得
     record = {'UserId':self.uid,'UserLevel':userInfo['UserLevel'],
               'UserType':Gcore.getUserData(self.uid,'UserType'),
               'Action':actionType,'HonourNumber':abs(honourValue),'OptId':optId,
               'NowHonour':updateVal,'CreateTime':time.time()}
     self.db.insert('tb_log_honour',record,isdelay=True)
     
     #记录成就
     if actionType==1:
         recordData = {'ValType':0,'Val':honourValue}
         Gcore.getMod('Building_home',self.uid).achieveTrigger(5,recordData)
         Gcore.getMod('Mission',self.uid).missionTrigger(5,recordData)
         
     return honourValue
Example #26
0
 def GainCoin(self,optId,coinType,coinValue,classMethod,param=''):
     ''' 获取货币
     @param optId:协议号
     @param coinType:货币类型 1,2,3,4
     @param coinValue: 货币值
     @param classMethod: 类和方法 class.method
     @param param: 参数
     @return:
         False 获取货币失败
         int   获得的货币数量
     '''
     
     if isinstance(param,(tuple,dict)):
         param = json_encode(param)
         
     coinType = int(coinType)
     if coinType==1:
         table = 'tb_user'
         field = 'GoldCoin'
     elif coinType==2:    
         table = 'tb_currency'
         field = 'Jcoin'
     elif coinType==3:
         table = 'tb_currency'
         field = 'Gcoin'
     elif coinType==4:
         table = 'tb_currency'
         field = 'Mcoin'
     
     MyCoin = self.getCoinNum(coinType)
     NowCoin = MyCoin+coinValue
     isFull = False
     
     if coinType==2 or coinType==3:
         storageSpace = Gcore.getMod('Building', self.uid).cacStorageSpace(coinType)
         if NowCoin > storageSpace:#存满
             isFull = True
             NowCoin = storageSpace
             coinValue = storageSpace - MyCoin #增加的数值
     
     if MyCoin == NowCoin: #没有可增空间
         print ' >> CoinMod Coin full GainCoin fail coinType:%s %s'%(coinType,coinValue)
         return 0
     
     #sql = "UPDATE "+table+" SET "+field+"=%s WHERE UserId='%s'"%(NowCoin,self.uid)
     sql = "UPDATE "+table+" SET "+field+"="+field+"+"+str(coinValue)+" WHERE UserId='%s'"%self.uid
     result = self.db.execute(sql)
     if not result:
         return -2
     else:
         #记录日志 
         table = 'tb_log_coin_%s'%coinType
         d = {}
         d['OptId'] = optId
         d['UserId'] = self.uid
         d['UserType'] = Gcore.getUserData(self.uid,'UserType')
         d['UserLevel'] = Gcore.getUserData(self.uid, 'UserLevel')
         d['OldCoin'] = MyCoin
         d['CoinNumber'] = coinValue
         d['Action'] = 1 # 1获得 2消耗
         d['NowCoin'] = NowCoin
         d['Func'] = classMethod
         d['Param'] = str(param)
         d['CreateTime'] = int(time.time())
         print ' >>> Logging CoinMod.GainCoin',d
         self.db.insert(table,d,isdelay=False) #货币日志不采用延迟插入,怕丢
         Gcore.getMod('Event',self.uid).gainCoinTrigger(optId,coinType,coinValue,NowCoin,isFull)
         return coinValue #当前拥有大于容量时候会返回负值
Example #27
0
 def getUserCamp(self):
     '''获取我的阵营,#@todo使用缓存'''
     #return self.db.out_field('tb_user','UserCamp','UserId=%s'%self.uid)
     return Gcore.getUserData(self.uid, 'UserCamp')
Example #28
0
    def PayCoin(self, optId, coinType, coinValue, classMethod, param=''):
        ''' 使用货币
        @param optId:协议号
        @param coinType:货币类型 1,2,3,4
        @param coinValue: 货币值
        @param classMethod: 类和方法 class.method
        @param param: 参数
        @return:
             1:成功
            -1:输入货币类型或货币值异常,非法操作 
            -2: 货币不足
            -3:支付失败
        '''
        if isinstance(param, (tuple, dict)):
            param = json_encode(param)

        coinType = int(coinType)
        if coinType == 1:
            table = 'tb_user'
            field = 'GoldCoin'
            #Vip黄金消耗折扣  add by zhanggh 5.28

            vipLevel = Gcore.getUserData(self.uid, 'VipLevel')
            discount = Gcore.getCfg('tb_cfg_vip_up', vipLevel, 'Discount')
            discount = discount if discount else 1
            print '未打折前', coinValue
            print 'vip折扣是', discount

            coinValue = math.ceil(coinValue * discount)

        elif coinType == 2:
            table = 'tb_currency'
            field = 'Jcoin'
        elif coinType == 3:
            table = 'tb_currency'
            field = 'Gcoin'
        elif coinType == 4:
            table = 'tb_currency'
            field = 'Mcoin'
        else:
            return -1

        if coinValue <= 0:
            return -1

        MyCoin = self.getCoinNum(coinType)
        #print '当前货币数量', MyCoin
        if MyCoin < coinValue:  #货币不足
            return -2
        else:
            NowCoin = MyCoin - coinValue
            #sql = "UPDATE "+table+" SET "+field+"=%s WHERE UserId='%s'"%(NowCoin,self.uid) #并发有问题
            sql = "UPDATE " + table + " SET " + field + "=" + field + "-" + str(
                coinValue) + " WHERE " + field + ">=" + str(
                    coinValue) + " AND UserId='%s'" % self.uid
            print '支付货币:', sql

            result = self.db.execute(sql)
            if not result:
                return -3
            else:
                #记录日志
                table = 'tb_log_coin_%s' % coinType
                d = {}
                d['OptId'] = optId
                d['UserId'] = self.uid
                d['UserType'] = Gcore.getUserData(self.uid, 'UserType')
                d['UserLevel'] = Gcore.getUserData(self.uid, 'UserLevel')
                d['OldCoin'] = MyCoin
                d['CoinNumber'] = coinValue
                d['Action'] = 2  # 1获得 2消耗
                d['NowCoin'] = NowCoin
                d['Func'] = classMethod
                d['Param'] = str(param)
                d['CreateTime'] = int(time.time())
                print ' >>> Logging CoinMod.PayCoin', d
                self.db.insert(table, d, isdelay=False)  #货币日志不采用延迟插入,怕丢
                Gcore.getMod('Event',
                             self.uid).payCoinTrigger(optId, coinValue)
                return coinValue
Example #29
0
    def GainCoin(self, optId, coinType, coinValue, classMethod, param=''):
        ''' 获取货币
        @param optId:协议号
        @param coinType:货币类型 1,2,3,4
        @param coinValue: 货币值
        @param classMethod: 类和方法 class.method
        @param param: 参数
        @return:
            False 获取货币失败
            int   获得的货币数量
        '''

        if isinstance(param, (tuple, dict)):
            param = json_encode(param)

        coinType = int(coinType)
        if coinType == 1:
            table = 'tb_user'
            field = 'GoldCoin'
        elif coinType == 2:
            table = 'tb_currency'
            field = 'Jcoin'
        elif coinType == 3:
            table = 'tb_currency'
            field = 'Gcoin'
        elif coinType == 4:
            table = 'tb_currency'
            field = 'Mcoin'

        MyCoin = self.getCoinNum(coinType)
        NowCoin = MyCoin + coinValue
        isFull = False

        if coinType == 2 or coinType == 3:
            storageSpace = Gcore.getMod('Building',
                                        self.uid).cacStorageSpace(coinType)
            if NowCoin > storageSpace:  #存满
                isFull = True
                NowCoin = storageSpace
                coinValue = storageSpace - MyCoin  #增加的数值

        if MyCoin == NowCoin:  #没有可增空间
            print ' >> CoinMod Coin full GainCoin fail coinType:%s %s' % (
                coinType, coinValue)
            return 0

        #sql = "UPDATE "+table+" SET "+field+"=%s WHERE UserId='%s'"%(NowCoin,self.uid)
        sql = "UPDATE " + table + " SET " + field + "=" + field + "+" + str(
            coinValue) + " WHERE UserId='%s'" % self.uid
        result = self.db.execute(sql)
        if not result:
            return -2
        else:
            #记录日志
            table = 'tb_log_coin_%s' % coinType
            d = {}
            d['OptId'] = optId
            d['UserId'] = self.uid
            d['UserType'] = Gcore.getUserData(self.uid, 'UserType')
            d['UserLevel'] = Gcore.getUserData(self.uid, 'UserLevel')
            d['OldCoin'] = MyCoin
            d['CoinNumber'] = coinValue
            d['Action'] = 1  # 1获得 2消耗
            d['NowCoin'] = NowCoin
            d['Func'] = classMethod
            d['Param'] = str(param)
            d['CreateTime'] = int(time.time())
            print ' >>> Logging CoinMod.GainCoin', d
            self.db.insert(table, d, isdelay=False)  #货币日志不采用延迟插入,怕丢
            Gcore.getMod('Event',
                         self.uid).gainCoinTrigger(optId, coinType, coinValue,
                                                   NowCoin, isFull)
            return coinValue  #当前拥有大于容量时候会返回负值
Example #30
0
    def setHold(self, PeerUID, PeerSID):
        '''设置别人成为藩国'''
        #根据配置得出自动解除的天
        HoldConfig = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD)
        RemoveRatio = HoldConfig['RemoveRatio']
        d = None
        for ind in range(1, len(RemoveRatio) + 1, 1):
            r = random.random()
            if  r <= RemoveRatio[str(ind)]:
                d = ind
                break

        #初始化元数据
        BeginTime = int(time.time()) #开始时间
        EndTime = BeginTime + int(d * 24 * 60 * 60) #预计结束时间(自动解除时间)
        # + StopTime是真正结束的时间:默认是EndTime
        # + LastCollectTime是最近一次奴隶的自动收集资源时间
        StopTime, LastCollectTime = EndTime, BeginTime    
        Jcoin, Gcoin = 0, 0 #奴隶的贡献
        
        print '是否是本服', PeerSID == self.serverid, PeerSID, self.serverid
        if PeerSID == self.serverid: #本服
            print '本服'
            pMod = Gcore.getMod('Player', PeerUID)
            protectHoldEndTime = pMod.getUserInfo('ProtectHoldEndTime')
            if BeginTime < protectHoldEndTime:
                return -1   #对方处于保护时间内,设置失败add by qiudx
            
            Data = Gcore.getMod('Building_resource',PeerUID).collectAll() #将地里的资源以自由身的身份收集一次
            Data['HoldEndTime'] = EndTime if not Gcore.TEST else int(time.time()+180)
            Data['HolderName'] = Gcore.getUserData(self.uid,'NickName')
            Data['GiveRatio'] = Gcore.loadCfg(1506).get('GiveRatio',0.05)
            Gcore.push(112, PeerUID, Data,Type=1)
            
            # + 更新用户表
            arr = {'HolderId':self.uid,'HolderServerId':self.serverid,'HoldEndTime':EndTime}
            self.db.update('tb_user', arr, 'UserId=%s' % PeerUID)
            # + 插入本服藩国记录
            arr = {"HolderId":self.uid, "GiverId":PeerUID, "LastCollectTime":LastCollectTime,
                   "JcoinGive":Jcoin, "GcoinGive":Gcoin, "StopTime":StopTime, 
                   "BeginTime": BeginTime, "EndTime":EndTime}
            #self.db.insert('tb_hold', arr)
            self.db.insert_update('tb_hold', arr, {"GiverId":PeerUID} )
            
            # + 插入纳贡记录
            arr = {"UserId":PeerUID, "HolderId":self.uid, "Gcoin":0,
                   "HolderServerId":self.serverid, "Jcoin":0, "LastGiveTime":BeginTime}
            self.db.insert_update('tb_hold_log', arr, {"UserId":PeerUID} )
            
            # + 插入藩国反抗记录
            date = datetime.date.strftime(datetime.date.fromtimestamp(BeginTime), "%Y-%m-%d")
            arr = {"UserId":PeerUID, "HolderId":self.uid, "HolderServerId":self.serverid,
                   "ProcessTotal":0, "RevengeCount":0, "LastRevengeDate":date}
            self.db.insert_update('tb_hold_revenge', arr, {"UserId":PeerUID} )
        else: #非本服,发消息
            peerKey = Gcore.redisKey(PeerUID)
            protectHoldEndTime = Gcore.redisM.hget('sgProtectHold', peerKey)
            if BeginTime < protectHoldEndTime:
                return -1   #潘国保护时间内,设置失败
            Gcore.sendmq(1, PeerSID, {'HolderId':self.uid,
                                      'HolderServerId':self.serverid,
                                      'GiverId':PeerUID,
                                      'EndTime':int(EndTime)})
        k = '%s.%s' % (PeerSID, PeerUID)
        v = '%s.%s.%s.%s.%s.%s' % (self.serverid, self.uid, BeginTime, StopTime, EndTime, LastCollectTime)
        Gcore.redisM.hset('sgHold', k, v) #货币相关已独立出来 by Lizr
        k += Gcore.redisKey(self.uid)
        Gcore.redisM.hset('sgHoldJcoin', k, 0) #1.1008.2.1001  前面是进贡的人 后面的纳贡的人
        Gcore.redisM.hset('sgHoldGcoin', k, 0)
        return True
Example #31
0
    def addUserExp(self, getWay, amount=0, optId=0):
        '''
        :增加主角经验(动作触发)
        @param getWay: 用户获得经验方式0:直接加经验,1-99:消耗加经验 101-199: 事件加经验
        @param amount: if getWay==0:amount='增加的经验值';elif 1<1getWay<99:amount='消耗货币量';
        @return: 返回主角经验等级,当前经验
        '''

        expCfg = Gcore.getCfg('tb_cfg_exp_get', getWay)
        fields = ['UserLevel', 'UserExp']
        userInfo = self.db.out_fields('tb_user', fields,
                                      'UserId=%s' % self.uid)
        userLevel = userInfo['UserLevel']
        userExp = userInfo['UserExp']
        getExp = 0

        if expCfg:  #动作增加经验方式
            segment = getWay / 100  #判断是消耗还是事件
            if segment == 0:  #消耗
                factor1 = expCfg.get('Factor1', 0)
                factor2 = expCfg.get('Factor2', 0)
                getExp = int(factor1 * amount + factor2 * userLevel)

            elif segment == 1 and self._getLimitOfEvent(getWay):  #事件
                baseExp = expCfg.get('BaseExp', 0)
                getExp = int(baseExp * (userLevel + 1) *
                             (1 + userLevel / 200.0) + 1)

        elif getWay == 0:  #直接加经验
            getExp = amount

        #增加经验,同时更新等级
        if getExp > 0:
            updateExp = self._calUserLevel(userLevel, userExp + getExp)
            self.db.update('tb_user', updateExp, 'UserId=%s' % self.uid)
            newLevel = updateExp.get('UserLevel')

            #获得经验记录
            logData = {
                'UserId': self.uid,
                'GetWay': getWay,
                'OptId': optId,
                'UserType': Gcore.getUserData(self.uid, 'UserType'),
                'UserLevel': newLevel,
                'ExpValue': getExp,
                'CreateTime': time.time()
            }
            self.db.insert('tb_log_exp', logData, isdelay=True)

            #主角升级
            if newLevel > userLevel:
                #升级推送
                Gcore.push(108, self.uid, {'UserLevel': newLevel})
                mMod = Gcore.getMod('Mission', self.uid)
                mMod.getNewMission(userLevel=newLevel)  #用户升级查看有没有新任务
                Gcore.setUserData(self.uid,
                                  {'UserLevel': newLevel})  #更新缓存中的用户等级  Lizr
                Gcore.getMod('General', self.uid).touchGeneralLv(newLevel)
                Gcore.getMod('War',
                             self.uid).touchActPoint(userLevel,
                                                     newLevel)  #更新行动力
                modActivity = Gcore.getMod('Activity', self.uid)  #报错
                modActivity.growUpAward(newLevel, userLevel)  #成长奖励活动Yew
                if newLevel >= Gcore.loadCfg(Gcore.defined.CFG_RANK_FIGHT).get(
                        'RankFightOpenLevel', 20):
                    Gcore.getMod('RankFight',
                                 self.uid).joinRankFight()  #每次升级都尝试加入排行榜 防止有漏

            return updateExp
        else:
            return userInfo
Example #32
0
 def getUserLevel(self):
     '''获取主角等级'''
     #return self.db.out_field('tb_user','UserLevel','UserId=%s'%self.uid)
     return Gcore.getUserData(self.uid, 'UserLevel')
Example #33
0
 def getUserCamp(self):
     '''获取我的阵营,#@todo使用缓存'''
     #return self.db.out_field('tb_user','UserCamp','UserId=%s'%self.uid)
     return Gcore.getUserData(self.uid, 'UserCamp')
Example #34
0
 def getUserLevel(self):
     '''获取主角等级'''
     #return self.db.out_field('tb_user','UserLevel','UserId=%s'%self.uid)
     return Gcore.getUserData(self.uid, 'UserLevel')
Example #35
0
    def PayCoin(self,optId,coinType,coinValue,classMethod,param=''):
        ''' 使用货币
        @param optId:协议号
        @param coinType:货币类型 1,2,3,4
        @param coinValue: 货币值
        @param classMethod: 类和方法 class.method
        @param param: 参数
        @return:
             1:成功
            -1:输入货币类型或货币值异常,非法操作 
            -2: 货币不足
            -3:支付失败
        '''
        if isinstance(param, (tuple,dict)):
            param = json_encode(param)
            
        coinType = int(coinType)
        if coinType==1:
            table = 'tb_user'
            field = 'GoldCoin'
            #Vip黄金消耗折扣  add by zhanggh 5.28
            
            vipLevel = Gcore.getUserData(self.uid, 'VipLevel')
            discount = Gcore.getCfg('tb_cfg_vip_up',vipLevel,'Discount')
            discount = discount if discount else 1
            print '未打折前', coinValue
            print 'vip折扣是', discount
            
            coinValue = math.ceil(coinValue*discount)
            
        elif coinType==2:    
            table = 'tb_currency'
            field = 'Jcoin'
        elif coinType==3:
            table = 'tb_currency'
            field = 'Gcoin'
        elif coinType==4:
            table = 'tb_currency'
            field = 'Mcoin'
        else:
            return -1

        if coinValue<=0:
            return -1
        
        MyCoin = self.getCoinNum(coinType)
        #print '当前货币数量', MyCoin
        if MyCoin<coinValue: #货币不足
            return -2 
        else:
            NowCoin = MyCoin-coinValue
            #sql = "UPDATE "+table+" SET "+field+"=%s WHERE UserId='%s'"%(NowCoin,self.uid) #并发有问题
            sql = "UPDATE "+table+" SET "+field+"="+field+"-"+str(coinValue)+" WHERE "+field+">="+str(coinValue)+" AND UserId='%s'"%self.uid
            print '支付货币:',sql
            
            result = self.db.execute(sql)
            if not result:
                return -3
            else:
                #记录日志 
                table = 'tb_log_coin_%s'%coinType
                d = {}
                d['OptId'] = optId
                d['UserId'] = self.uid
                d['UserType'] = Gcore.getUserData(self.uid,'UserType')
                d['UserLevel'] = Gcore.getUserData(self.uid, 'UserLevel')
                d['OldCoin'] = MyCoin
                d['CoinNumber'] = coinValue
                d['Action'] = 2 # 1获得 2消耗
                d['NowCoin'] = NowCoin
                d['Func'] = classMethod
                d['Param'] = str(param)
                d['CreateTime'] = int(time.time())
                print ' >>> Logging CoinMod.PayCoin',d
                self.db.insert(table,d,isdelay=False) #货币日志不采用延迟插入,怕丢
                Gcore.getMod('Event',self.uid).payCoinTrigger(optId,coinValue)
                return coinValue