Ejemplo n.º 1
0
 def checkAndUpdate(self, table):
     '''查找并更新数据库中建筑费用为NULL的数据'''
     fields = ['BuildingId', 'UserId', 'BuildingType', 'BuildingLevel', 'CoinType', 'BuildingPrice', 'LastChangedTime', 'CompleteTime']
     where = ' CoinType is NULL or BuildingPrice is NULL or LastChangedTime is NULL OR CoinType = 0 OR BuildingPrice = 0 '
     tmpRows = self.db.out_rows(table, fields, where)
     if tmpRows:
         for row in tmpRows:
             #print '==PrimaryData:',row
             tmpData = json.dumps(row) + '\n'
             self.fd.write(tmpData)
             if not row['CoinType']:
                 row['CoinType'] = Gcore.getCfg('tb_cfg_building', row['BuildingType'], 'CoinType')
             if not row['BuildingPrice']:
                 row['BuildingPrice'] = Gcore.getCfg('tb_cfg_building_up', (row['BuildingType'], row['BuildingLevel']), 'CostValue')
             if not row['LastChangedTime'] and row['LastChangedTime'] != 0:
                 if row['CompleteTime']:
                     row['LastChangedTime'] = row['CompleteTime'] - Gcore.getCfg('tb_cfg_building_up', (row['BuildingType'], row['BuildingLevel']), 'CDValue')
                 else:
                     row['LastChangedTime'] = 0
                 if row['LastChangedTime'] < 0:
                     row['LastChangedTime'] = 0
             where = 'BuildingId=%s'%row['BuildingId']
             data = {'CoinType': row['CoinType'], 'BuildingPrice': row['BuildingPrice'], 'LastChangedTime': row['LastChangedTime']}
             self.db.update(table, data, where)
             #print '==ModifiedData:',data
             tmpData = json.dumps(data) + '\n'
             self.fd.write(tmpData)
Ejemplo n.º 2
0
    def GetPatchNum(self, para={}):
        """获取碎片的数量"""
        optId = 15132

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

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

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

        return Gcore.out(optId, rels)
Ejemplo n.º 3
0
    def autoAddSoldier(self, TimeStamp=None):
        '''自动补兵'''
        TimeStamp = TimeStamp if TimeStamp else time.time()

        #上阵武将的信息
        Generals = self.getLatestGeneralInfo(TimeStamp=TimeStamp)
        onembattle = sorted([General for General in Generals if General["PosId"] and \
                           General["TakeType"]], key=lambda dic:dic["PosId"])
        if not onembattle:
            return -1 #没有上阵武将

        #当前士兵总数
        modCamp = Gcore.getMod('Building_camp', self.uid)
        soldiers = modCamp.getSoldiers()

        #剩余的士兵
        for General in onembattle:
            soldiers["Soldier%d"%General['TakeType']] -= General['TakeNum']
            assert soldiers["Soldier%d"%General['TakeType']] >= 0

        kLeaderAddNum = Gcore.loadCfg(Gcore.defined.CFG_BATTLE).get('kLeaderAddNum')
        sql = 'UPDATE %s SET TakeNum=CASE GeneralId ' % self.tb_general()
        for General in onembattle:
            num = min(soldiers["Soldier%d"%General['TakeType']],
                      General['LeaderValue'] * kLeaderAddNum - General["TakeNum"])
            General["TakeNum"] += num
            soldiers["Soldier%d"%General['TakeType']] -= num
            sql += ' WHEN %d THEN %d ' % (General["GeneralId"], General["TakeNum"])

        where = 'UserId = %s AND ( GeneralId = ' % (self.uid, )+ \
        ' OR GeneralId = '.join([str(General["GeneralId"]) for General in onembattle]) + ' ) '
        sql += ' ELSE TakeNum END WHERE %s ' % where

        return self.db.execute(sql)
Ejemplo n.º 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 []
Ejemplo n.º 5
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, {})
Ejemplo n.º 6
0
 def _getDropShowList(self):
     '''获得高级掉落物品列表,在打战役前显示'''
     showDict = {}
     for k,rows in Gcore.getCfg('tb_cfg_pve_drop').iteritems():
         DropId,Star = k
         
         if DropId not in showDict:
             showDict[DropId] = []
         for row in rows:
             if row['Ratio'] == 0:
                 continue
             row['RewardType'] = int(row['RewardType'])
             if row['RewardType'] in (1,2,4,5,6):
                 cell = {'RewardType':row['RewardType'],'GoodsId':row['GoodsId']}
                 if row['RewardType'] == 1: #装备
                     Quality = Gcore.getCfg('tb_cfg_equip',row['GoodsId'],'Quality')
                     if Quality>=2: #紫装以上
                         if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 elif row['RewardType'] == 2: #道具
                     Quality = Gcore.getCfg('tb_cfg_item',row['GoodsId'],'ItemQuality')
                     if Quality>0: #全掉 
                         if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 else:
                     if cell not in showDict[DropId]:
                             showDict[DropId].append(cell)
                 
         #break
     for DropId in showDict:
         showDict[DropId] =  Gcore.common.list2dict(showDict[DropId])  
     
     return showDict
Ejemplo n.º 7
0
    def getLatestGeneralInfo(self, Generals=None, TimeStamp=None, UserLevel=None, 
                             GeneralIds=None, fields='*', IsClubTech=True):
        '''获取玩家武将的最新信息'''
        # 参数:
        # + Generals - 武将表中所有武将的信息
        # + fields - 已取消,兼容以前的程序,现返回所有的字段
        # + GeneralIds - 要查询的武将
        # + + int, long, str - 查询单个武将的信息
        # + + list, tuple - 查询多个武将的信息
        # + + None - 查询玩家所有武将的信息
        # + IsClubTech - 是否加上军团科技和宝物对武将四维属性的加成
        
        # 返回值:
        # + 单个武将:dict or None
        # + 多个武将:list
        # + 都不是:False

        if not TimeStamp:TimeStamp = time.time()
        if not Generals:Generals = self.getMyGenerals()
        if not UserLevel:UserLevel = self.getUserLevel()
        
        #加上武馆训练的经验
        modGround = Gcore.getMod('Building_ground', self.uid)
        _, Generals = modGround.touchPractise(Generals, TimeStamp, UserLevel)
        
        if IsClubTech: #四维属性加上各种加成
            # + 军团科技影响
            modClub = Gcore.getMod('Building_club', self.uid)
            club_tech_effects = modClub.getClubTechAdd()

            # + 宝物影响
            treasure_effects = self.getEquipExEffect([General['GeneralId'] for General in Generals])

            # + 四维加上各种加成
            for General in Generals:
                General["ForceValue"] += int(club_tech_effects[1])
                General["WitValue"] += int(club_tech_effects[2])
                General["LeaderValue"] += int(club_tech_effects[3])
                General["SpeedValue"] += int(club_tech_effects[4])

                treasure_effect = treasure_effects[General['GeneralId']]
                General["ForceValue"] += int(General["ForceValue"] * treasure_effect['force'])
                General["WitValue"] += int(General["WitValue"] * treasure_effect['wit'])
                General["SpeedValue"] += int(General["SpeedValue"] * treasure_effect['speed'])
                General["LeaderValue"] += int(General["LeaderValue"] * treasure_effect['leader'])

        if not GeneralIds: #返回所有武将的信息
            return Generals
        elif isinstance(GeneralIds, (int, long, str)): #返回单个武将的信息
            for General in Generals:
                if General["GeneralId"] == int(GeneralIds):
                    return General
            return None
        elif isinstance(GeneralIds, (list, tuple)): #返回多个武将的信息
            ret = []
            for General in Generals:
                if General["GeneralId"] in map(int, GeneralIds):
                    ret.append(General)
            return ret
        return False
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
 def getActPoint(self):
     '''获得 剩余行动点数/最大行动点数'''
     BuyActPoint = self.getUserInfo('BuyActPoint')
     row = self._lastActRecord()
     MaxPoint = Gcore.getCfg('tb_cfg_action_point',self.getUserLevel(),'ActPoint')
     if not row:
         RestPoint = MaxPoint + BuyActPoint
     else:
         nowtime = Gcore.common.nowtime()
         PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime',1200)
         if Gcore.TEST and self.uid in [1001,43953]:
             PerIncrTime = testPerIncrTime
         if row['ActPoint']>=MaxPoint: #已满,不恢复
             RestPoint = row['ActPoint']
         else:
             AccuTime = row['AccuTime'] + ( nowtime - row['LastWarTime'] )
             incrTimes = AccuTime//PerIncrTime #回复一点需要多长时间 20分钟
             #print 'incrTimes',incrTimes
             print 'getActPoint.上次剩余',row['ActPoint']
             print 'getActPoint.至已经恢复了',incrTimes
             ActPoint = row['ActPoint'] + incrTimes
             if ActPoint > MaxPoint:
                 ActPoint = MaxPoint
                 print 'getActPoint.剩余+累计越出上限,设为上限',ActPoint
                 
             #查看的时候 不更新累计时间 tb_war_action.AccuTime    
             RestPoint = ActPoint
         
     #print '剩余次数    最大次数',RestPoint,MaxPoint, 前台显示的是: 剩余次数/最大次数
     return (RestPoint,MaxPoint)
Ejemplo n.º 10
0
 def mqPush(self,ckey,optId,optKey,para):
     '''来自mqReceiver的消息,告诉玩家正在被打'''
     #print ' in mqPush',para
     Users = para.get('UserId')
     Type = para.get('Type')
     Data = para.get('Data',{})
     Gcore.push(105, Users, Data, Type)
Ejemplo n.º 11
0
 def __init__(self): 
     #self.validate = Validate()
     self.Clients = {} #所有用户信息库
     Gcore.objCfg.loadAllCfg() #读取所有配置
     Gcore.IsServer = True #定义为服务器核心
     
     Gcore.startNotice() #开启公告自动发布协程
Ejemplo n.º 12
0
 def CheckMissionStatus(self ,p={}):
     '''检查任务状态'''
     optId = 22005
     self.mod.updateAllMissions()
     
     Gcore.getMod('Building_home',self.uid).updateAllAchieves()
     return Gcore.out(optId)
Ejemplo n.º 13
0
 def sendMail(self, toUserIds, subject, content, mailUserType=2):
     '''
                  发送邮件
     @param toUserIds:发送对象Id,列表类型
     @param subject:标题
     @param content:内容
     @param mailUserType:邮件类型1为系统邮件,2为私人邮件
     @return 返回成功发送个数
     '''
     if mailUserType == 1:
         fromUserId = 0
     else:
         fromUserId = self.uid
     timeStamp = int(time.time())
     mailConId = self.insMailCon(content)
     result = 0
     if len(toUserIds) and mailConId:
         vals = []
         for toId in toUserIds:
             v = {}
             v['FromUserId'] = fromUserId
             v['ToUserId'] = toId
             v['Subject'] = subject
             v['MailConId'] = mailConId
             v['CreateTime'] = timeStamp
             v['MailUserType'] = mailUserType
             vals.append(v)
         
         result = self.db.insertmany('tb_mail', vals)
         Gcore.push(101, toUserIds)
     return result
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
    def randomName(self, icon):
        '''随机名称  '''
        SelectNum = 30
        if icon > 2:
            sex = 2
        else:
            sex = 1
        
        pMod = Gcore.getMod('Player', 1001)

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

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

        where = pMod.db.inWhere('NickName',nicknames)
        rows = pMod.db.out_rows('tb_user','NickName',where)
        existNickNames = [r['NickName'] for r in rows]
        notExistNickNames = list(set(nicknames)-set(existNickNames))
        
        NickNames = []
        for NickName in notExistNickNames:
            if Gcore.common.filterInput(NickName,2,16)<0:
                pass #过滤敏感词的名称
            else:
                NickNames.append(NickName)
        
        return NickNames[0]
Ejemplo n.º 16
0
 def GetMyTech(self,p={}):
     '''获取我学习的所有科技'''
     optId = 15051
     buildingId = p['BuildingId']
     building = Gcore.getMod('Building',self.uid).getBuildingById(buildingId)
     if not building:
         return Gcore.out(optId)
     buildingType = building.get('BuildingType')
     
     st = self.mod.getTechs(1)#兵种科技
     soldierTechs = []#书院研究科技
     wallTechs = []#城墙研究科技
     
     for k,v in enumerate(st):
         if v['TechType']>=200:
             wallTechs.append(v)
         else:
             soldierTechs.append(v)
     
     if buildingType==12:#书院
         interTechs = self.mod.getTechs(2)#内政科技     
         reData = {'SoldierTechs':soldierTechs,'InterTechs':interTechs}
     else:
         reData = {'WallTechs':wallTechs}
     return Gcore.out(optId,reData)
Ejemplo n.º 17
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})
Ejemplo n.º 18
0
 def GetSignInLog(self, param={}):
     '''获取签到日志'''
     optId = 23006
     data = self.mod.getSigninLog()
     a = list(data['SignInDate'])
     data['SignInDate'] = ','.join(a)
     #获取全勤奖励信息
     awards = Gcore.getCfg('tb_cfg_act_signin_award').values()
     fullWorkAwards = filter(lambda dic:dic['AwardId']>=3000 and dic['AwardId']<4000, awards)
     now = datetime.datetime.now()
     data['FullWorkAwardId'] = fullWorkAwards[now.month-1]['AwardId']
     #获取周期奖励信息
     finalAwards = Gcore.loadCfg(CFG_ACT_SIGNIN)['FinalAwardId']
     #awards = finalAwards.split(',')
     awards = finalAwards
     signCount = data['SignInCount']
     n = signCount / 30 % len(awards)
     if signCount % 30 == 0:
         n -= 1
     awardId = int(awards[n])
     data['FinalAwardId'] = awardId
     signCount = signCount % 30
     data['SignInDays'] = signCount if signCount else 30 #用于前台显示当前周期内的天数,30天一周期
     data['Refill'] = 5 - data['Refill']
     return Gcore.out(optId, data)
Ejemplo n.º 19
0
 def GetActivitiesUI(self, param={}):
     '''返回参数1首次充值2签到3成长奖励4活跃度礼包5鸿运当头6在线奖励'''
     optId = 23001
     activities = Gcore.getCfg('tb_cfg_act')
     data = {}
     acts = []
     for act in activities:
         if activities[act]['Status'] == 1:
             actId = activities[act]['ActivityId']
             if actId == 1:#首冲活动
                 playerMod = Gcore.getMod('Player',self.uid)
                 vipTotalPay = playerMod.getUserBaseInfo(['VipTotalPay']).get('VipTotalPay')
                 if vipTotalPay:
                     giftState = self.mod.getGift(1, 0, ['isGet']).get('isGet')
                     data['Recharged'] = 1 if giftState == 0 else 0
                 else:
                     data['Recharged'] = 1 #新号要显示首冲活动
                     
                 if not data['Recharged']: #1表示可以领首冲礼包或者新号显示首冲活动,0表示不显示
                     continue
             elif actId == 5:
                 luckyLog = self.mod.getLuckLog()
                 luckyLog['AwardId'] += 1
                 goodLuckCfg = Gcore.getCfg('tb_cfg_act_lucky_award', luckyLog['AwardId'])
                 if not goodLuckCfg:
                     continue
             acts.append(actId)
     data['Activities'] = acts
     return Gcore.out(optId, data)
Ejemplo n.º 20
0
    def getWallGeneralList(self):
        '''获取布防武将列表  参考getWallGeneralList()  
        @call: WallUI
        @author: by Lizr
        '''
        kLeader = Gcore.loadCfg(Gcore.defined.CFG_BATTLE)["kLeaderAddNum"]
        SoldierTechs =  Gcore.getMod('Book',self.uid).getTechsLevel(1)
        
        InListGeneral = self.db.out_list('tb_wall_general','GeneralId',"UserId=%s"%self.uid) #已布防
        
        fields = ['GeneralId','GeneralType','GeneralLevel','ForceValue',
                  'WitValue','SpeedValue','LeaderValue','TakeType','TakeTypeDefense']
        rows = Gcore.getMod('General',self.uid).getMyGenerals(fields)
        #Gcore.printd( rows )
        GeneralList = []
        for row in rows:
            if not row['TakeTypeDefense']:
                row['TakeTypeDefense'] = row['TakeType']

            row['Skill'] = Gcore.getCfg('tb_cfg_general',row['GeneralType'],'SkillId')
            SoldierType = row['TakeTypeDefense']
            SoldierLevel = SoldierTechs.get( SoldierType )
            row['SoldierType'] = SoldierType
            row['SoldierLevel'] = SoldierLevel
            key = (SoldierType,SoldierLevel)
            SoldierNum = row['LeaderValue']*kLeader
            
            cfg_soldier = Gcore.getCfg('tb_cfg_soldier_up',key)
            if cfg_soldier:
                #row['Life'] = cfg_soldier['Life']* row['LeaderValue']*kLeader
                #row['Attack'] = cfg_soldier['Attack']*row['LeaderValue']*kLeader
                #row['Denfense'] = cfg_soldier['Defense']
                
                row['Life'] = F.getArmyLife(cfg_soldier['Life'], SoldierNum)
                row['Attack'] = F.getArmyAttack(
                                               generalType = row['GeneralType'],
                                               soldierType = row['SoldierType'],
                                               landForm = 4,
                                               soldierAttack = cfg_soldier['Attack'],
                                               soldierNum = SoldierNum,
                                               forceValue = row['ForceValue'],
                                               )
                row['Denfense'] = F.defenseAdd( cfg_soldier['Defense'],row['SpeedValue'],row['GeneralType']) 
            else:
                row['Life'] = 0
                row['Attack'] = 0
                row['Denfense'] = 0
                
            row['InWall'] = row['GeneralId'] in InListGeneral #是否在布防中
            
#            del row['ForceValue']
#            del row['WitValue']
#            del row['SpeedValue']
#            del row['LeaderValue']
            
            del row['TakeType']
            del row['TakeTypeDefense']
           
            GeneralList.append(row)
        return GeneralList
Ejemplo n.º 21
0
    def BuyMap(self,p={}):
        '''购买地图'''

        optId = 14002
        if 'x' not in p or 'y' not in p:
            return Gcore.error(optId,-14002001) #非法参数 
        
        x = p['x']
        y = p['y']
        if not self.mod.checkBuyStartCoord(x,y):
            print self.mod.db.sql
            return Gcore.error(optId,-14002002) #所传的坐标非可购买坐标的起点
            
        if self.mod.checkHadBuy(x,y):
            return Gcore.error(optId,-14002003) #你已经购买过此坐标
        
        MapBuyTimes = Gcore.getMod('Player',self.uid).getMapBuyTimes()
        CostValue = Gcore.getCfg('tb_cfg_map_cost',MapBuyTimes,'Cost')
        print CostValue
        #开始支付
        modCoin = Gcore.getMod('Coin',self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, 3, CostValue, classMethod, p)
        achieve = {'uid':self.uid,'ValType':0,'Val':1}#成就记录
        if pay < 0:
            Gcore.error(optId, -14002995) #支付失败
        else:
            if not self.mod.doBuyMap(x,y):
                return Gcore.error(optId,-14002004) #购买失败
            else:
                return Gcore.out(optId,achieve=achieve)
Ejemplo n.º 22
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) #没有可回收的防御工事
Ejemplo n.º 23
0
 def mqPush(self, ckey, optId, optKey, para):
     """来自mqReceiver的消息,告诉玩家正在被打"""
     # print ' in mqPush',para
     Users = para.get("UserId")
     Type = para.get("Type")
     Data = para.get("Data", {})
     Gcore.push(105, Users, Data, Type)
Ejemplo n.º 24
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)
Ejemplo n.º 25
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)
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
 def startSiege(self, para):
     '''开始城战'''
     optId = 93002
     body = self.mod.startSiege() #开始攻城战斗
     if not isinstance(body, dict):
         return Gcore.error(optId,body) #body 是错误编号 
     return Gcore.out(optId,body)
Ejemplo n.º 28
0
 def setReventProcess(self, process, flag=0, TimeStamp=None):
     '''设置反抗进度:process-攻城进度;flag-0失败,1成功'''
     #返回值:-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)
         hsid,huid = self.getMyHolder()
         if huid:
             self.freed(huid, hsid) #让自己被释放
             pMod = Gcore.getMod('Player', self.uid)
             protectTime = Gcore.loadCfg(CFG_BUILDING_HOLD)['RvProtectHoldSecond']
             pMod.addProtectHoldTime(protectTime)
         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)
Ejemplo n.º 29
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
Ejemplo n.º 30
0
 def sendSystemMail(self, toUserId, goods, optId, **param):
     '''
        toUserId: 收件人ID
        goods:  {‘GoodsType’:type, 'GoodsId': id, 'GoodsNum': num}组成的列表,没有附件则[]
        optId:  操作ID,用于查找邮件模板的ID
        param:  字典,格式如:{'subopt': subopt, 'other':[]}如果一个协议有两个操作,则需要用到subopt
        return: 返回邮件ID
     '''
     content = formatContent(optId, **param)
     if not content or not toUserId:
         return 0
     mailConId = self.insMailCon(content)
     timeStamp = int(time.time())
     data = {
             'FromUserId': 0,
             'Subject': content,
             'ToUserId': toUserId,
             'MailConId': mailConId,
             'CreateTime': timeStamp,
             'MailUserType': 1,}
         
     mailId = self.db.insert('tb_mail', data)
     
     if goods != []:
         for adict in goods:
             adict['MailId'] = mailId        
         self.db.insertmany('tb_attachment', goods)
     Gcore.push(101, toUserId)
     
     return mailId
Ejemplo n.º 31
0
 def __init__(self, uid):
     '''注释'''
     self.uid = uid
     self.mod = Gcore.getMod('Building_club', uid)
Ejemplo n.º 32
0
    #     d = c.CreateClub({"LogoId":1,"ClubName":'yoyoyo'})
    #    d = c.Devote({"CoinType":2,"CoinValue":1000})
    d = c.GetMyClub()


#     d = c.GetClubList({'PageNum':1})
#    d = c.GetMemberList({'PageNum':10,'SortField':2,'SortWay':1})
#    d = c.GetApplyMembers()
#    d = c.ModifyClub({'LogoId':2,'ClubNotice':"sdhfhewrherhe",'AllowState':1})
#     d = c.ApplyClub({'ClubId':3})
#    d = c.SetClubLeader({'UserId':1003})
#     d = c.AgreeApply({'UserId':43419})
#     d = c.DismissMember({'UserId':1003})
#    d = c.RefuseApply({'UserId':1003})
#     d = c.GetClubTechs()
#     d = c.UpgradeClubTech({'ClubTechType':1})
#    d = Gcore.getCfg('tb_cfg_club_up',1,'OpenLevelTech'+str(1))
#    d = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB ).get('BoxPS')
#     d = c.ExitClub()
#     c.GetCrewList({'ListView':1,'PageNum':1,'SortField':1,'SortWay':1})
#     c.OpenBox({'BoxType':2})

#     d = c.GetBoxLogs({'ListView':1,'PageNum':1})
#     Gcore.printd(d)
#     print Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost')
#     print c.GetDevoteLogs()

if __name__ == '__main__':
    _test()
    Gcore.runtime()
Ejemplo n.º 33
0
 def __init__(self):
     self.db = Gcore.getNewDB()
     self.fd = None  #将修改过的数据写入文件,备份,防止出错
Ejemplo n.º 34
0
# -*- coding:utf-8 -*-
# author:Lizr
# date:2013-8-8
# 比武排名快照,用于发奖励,每天10点运行

import time
from os.path import dirname,abspath

system_root = dirname(dirname( abspath( __file__ ) ) ) #定义上层目录为根目录 
import sys;sys.path.insert(0,system_root)  #把项目根目录加入默认库路径 

curtime = time.time()
from sgLib.core import Gcore

#=====Content Begin=======

db = Gcore.getDB()
sql = 'INSERT INTO tb_rank_fight_last (RankId,UserId) SELECT RankId,UserId FROM tb_rank_fight ON DUPLICATE KEY UPDATE UserId = VALUES(UserId)'
db.execute(sql)

sql = 'UPDATE tb_rank_fight_last SET Rewarded=0,RewardTime=NOW()'
db.execute(sql)

runtime = time.time()-curtime
print 'Finish at:',Gcore.common.now()
print 'Total Runtime:', runtime
Ejemplo n.º 35
0
    def SpeedupProcess(self, param={}):
        '''通用:加速建造或升级'''
        optId = 15004

        BuildingId = param["BuildingId"]
        if not BuildingId:
            x = param["x"]
            y = param["y"]
            BuildingId = self.mod.getBuildingByCoord(x, y)
        if not BuildingId:
            return Gcore.error(optId, -15004002)  #没有这个建筑
        TimeStamp = param['ClientTime']

        BuildingInfo = self.mod.getBuildingById(
            BuildingId,
            fields=['CompleteTime', 'BuildingType', 'BuildingLevel'],
            TimeStamp=TimeStamp)
        if not BuildingInfo:
            return Gcore.error(optId, -15004003)  #用户没有该建筑
        if BuildingInfo['BuildingState'] == 0:
            return Gcore.error(optId, -15004004)  #建筑已建造或升级完成
        BuildingType = BuildingInfo['BuildingType']
        BuildingLevel = BuildingInfo['BuildingLevel']

        StopTime = BuildingInfo['CompleteTime']
        TimeRemained = StopTime - TimeStamp
        GoldenCoinNum = common.calSpeedCost(1, TimeRemained)
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, 1, GoldenCoinNum, classMethod, param)
        if pay < 0:
            return Gcore.error(optId, -15004995)  #支付失败

        #更新建筑表
        UpInfo = {"CompleteTime": TimeStamp, "LastOptType": 3}
        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}
                modCamp.updateProcessById(update_dic, BuildingId)
        if BuildingType == 18:  #点将台
            print '点将台加速完成'
            modTrain = Gcore.getMod('Building_train', self.uid)
            if BuildingLevel == 1:
                num = Gcore.getCfg('tb_cfg_building_up', (18, 1), 'MakeValue')
            else:
                num = Gcore.getCfg('tb_cfg_building_up',
                                   (18, BuildingLevel),
                                   'MakeValue') - \
                      Gcore.getCfg('tb_cfg_building_up',
                                   (18, BuildingLevel-1),
                                   'MakeValue')
            print '增加的数量', num
            modTrain.normalAddTrainNum(num=num, TimeStamp=TimeStamp)

        recordData = {
            'uid': self.uid,
            'ValType': BuildingType,
            'Val': 1,
            'BuildingLevel': BuildingLevel
        }  #成就、任务记录
        return Gcore.out(optId, {
            'Coin%s' % 1: modCoin.getCoinNum(1),
            "Cost": pay,
            "TimeRemained": TimeRemained
        },
                         mission=recordData)
Ejemplo n.º 36
0
 def CountUnReadNum(self, param={}):
     optId = 18007
     num = self.mod.countUnReadNum()
     return Gcore.out(optId, {'UnReadNum': num})
Ejemplo n.º 37
0
 def __init__(self, uid):
     self.mod = Gcore.getMod('Mail', uid)
     self.uid = uid
Ejemplo n.º 38
0
    def InsMessage(self, param={}):
        '''
                    发送邮件
        '''
        import sys
        reload(sys)
        sys.setdefaultencoding('utf8')

        optId = 18006

        toUserNickNames = param['ToUserNickNames']  #收件人昵称字符串
        subject = param['Subject']
        content = param['Content']
        toUserNickNames = escapeSplit(toUserNickNames)  #解析昵称字符串
        if not subject or (not content) or (not toUserNickNames):
            return Gcore.error(optId, -18006003)  #邮件信息不完整

        mailCfg = Gcore.loadCfg(Gcore.defined.CFG_MAIL)
        subjectMin = mailCfg['SubjectMin']  #主题最小字符数
        subjectMax = mailCfg['SubjectMax']  #主题最大字符数
        contentMin = mailCfg['ContentMin']
        contentMax = mailCfg['ContentMax']
        toUserMax = mailCfg['MailSendMax']  #同时发送邮件最大数量

        toUserIds = self.mod.getToUserId(toUserNickNames)  #根据昵称,得到玩家id
        if not toUserIds:
            return Gcore.error(optId, -18006004)  #输入玩家昵称有误

        #最多同时发送邮件给五个玩家,最少一个
        numToUserId = len(toUserIds)
        if numToUserId > toUserMax:
            #不能超过5个玩家
            return Gcore.error(optId, -18006001)
        if self.uid in toUserIds:
            return Gcore.error(optId, -18006002)  #不能发信息给自己

        #过滤主题和邮件内容
        subject = filterInput(subject,
                              subjectMin,
                              subjectMax,
                              b_Replace=True,
                              b_chat=True)
        if subject == -1:
            return Gcore.error(optId, -18006993)  #长度不符合要求
        if subject == -2:
            return Gcore.error(optId, -18006991)  #特殊字符
        content = filterInput(content,
                              contentMin,
                              contentMax,
                              b_Replace=True,
                              b_chat=True)
        if content == -1:
            return Gcore.error(optId, -18006993)  #长度不符合要求
        if content == -2:
            return Gcore.error(optId, -18006991)  #特殊字符

        param['ToUserIds'] = toUserIds
        result = self.mod.sendMail(toUserIds, subject, content, 2)
        body = {'result': result}

        recordData = {
            'uid': self.uid,
            'ValType': numToUserId,
            'Val': 1
        }  #成就,任务记录
        return Gcore.out(optId, body=body, mission=recordData)
Ejemplo n.º 39
0
    def CreateBuilding(self, param={}):
        '''通用:建造建筑'''
        optId = 15001

        #参数
        BuildingType = param['BuildingType']
        x = param['x']
        y = param['y']
        TimeStamp = param['ClientTime']

        BuildingCfg = Gcore.getCfg('tb_cfg_building')
        if BuildingType==1 or BuildingType==19 or \
            BuildingType not in BuildingCfg:
            #非法操作:将军府和城墙不能建造 或 建筑类型不对。
            return Gcore.error(optId, -15001998)

        #建筑大小
        size = Gcore.getCfg('tb_cfg_building', BuildingType, 'Size')
        xSize, ySize = self.mod.sizeExplode(size)

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

        #已经被建筑占用的坐标
        modMap = Gcore.getMod('Map', self.uid)
        UsedCoords = modMap.cacUsedCoords(AllBuildings)
        #所有可用坐标
        UsefulCoords = modMap.getAllUsefulCoords()
        #要使用的坐标
        NeededCoords = modMap.getCoords(x, y, xSize)
        #检查坐标是否可用

        for CoordTpl in NeededCoords:
            if CoordTpl in UsedCoords or CoordTpl not in UsefulCoords:
                print CoordTpl, '不可用'
                print CoordTpl, '在已用坐标中:', CoordTpl in UsedCoords
                print CoordTpl, '不在可用坐标中:', CoordTpl not in UsefulCoords
                return Gcore.error(optId, -15001001)  #坐标不可用

        #将军府等级
        HomeLevel = 0
        for Building in AllBuildings:
            if Building['BuildingType'] == 1:
                HomeLevel = Building['BuildingRealLevel']

        #读配置
        OpenLevel = Gcore.getCfg('tb_cfg_building', BuildingType, 'OpenLevel')
        MaxNum = Gcore.getCfg('tb_cfg_building', BuildingType, 'MaxNum')
        ExpandLevelJson = Gcore.getCfg('tb_cfg_building', BuildingType,
                                       'ExpandLevelJson')

        if HomeLevel < OpenLevel:
            return Gcore.error(optId, -15001002)  #未达到开放等级

        #空闲工匠数量
        AllWorkerNum = self.mod.getWorkerNum()
        BusyWorkerNum = len([
            Building for Building in AllBuildings
            if Building['BuildingState'] != 0
        ])
        FreeWorkerNum = AllWorkerNum - BusyWorkerNum
        if FreeWorkerNum <= 0:
            return Gcore.error(optId, -15001003)  #无空闲工匠

        #该类型建筑的数量
        countBuildingType = len([
            Building for Building in AllBuildings
            if Building['BuildingType'] == BuildingType
        ])
        if countBuildingType >= MaxNum:
            return Gcore.error(optId, -15001004)  #已达到最大建筑数量

        #扩建个数
        if ExpandLevelJson:
            ExpandLevelDict = json.loads(ExpandLevelJson)
            MaxCanBuild = [
                int(num) for num, Level in ExpandLevelDict.iteritems()
                if HomeLevel >= Level
            ]
            if MaxCanBuild and countBuildingType >= max(MaxCanBuild):
                return Gcore.error(optId, -15001005)  #扩建失败

        CostValue = Gcore.getCfg('tb_cfg_building_up', (BuildingType, 1),
                                 'CostValue')
        CDValue = Gcore.getCfg('tb_cfg_building_up', (BuildingType, 1),
                               'CDValue')  #建筑建造时间
        CoinType = Gcore.getCfg('tb_cfg_building', BuildingType, 'CoinType')

        #建筑CD时间受内政4影响, 花费受内政7影响#Author:Zhanggh 2013-4-23
        interMod = Gcore.getMod('Inter', self.uid)
        CDValue = interMod.getInterEffect(4, CDValue)
        CostValue = interMod.getInterEffect(7, CostValue)

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

        param['xSize'], param['ySize'] = xSize, ySize
        param['CoinType'] = CoinType
        param['CostValue'] = CostValue
        param['CDValue'] = CDValue
        param['LastChangedTime'] = TimeStamp

        BuildingId = self.mod.createBuilding(param)
        if int(BuildingId) > 0:
            #不同类型的建筑向不同的表中插入初始数据
            return Gcore.out(
                optId, {
                    'Coin%s' % CoinType: modCoin.getCoinNum(CoinType),
                    'BuildingId': BuildingId,
                    'EndTime': TimeStamp + CDValue,
                    'x': param['x'],
                    'y': param['y'],
                    'BuildingType': BuildingType
                })
        return Gcore.error(optId, -15001997)  #系统错误
Ejemplo n.º 40
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)
            })
Ejemplo n.º 41
0
 def __init__(self, uid):
     self.mod = Gcore.getMod('Building', uid)
     self.uid = uid
Ejemplo n.º 42
0
    def UpgradeBuilding(self, param={}):
        '''通用:升级建筑'''
        print '建筑开始'
        import time
        starttime = time.time()
        optId = 15002

        BuildingId = param['BuildingId']
        TimeStamp = param['ClientTime']
        body = {}  #返回参数

        AllBuildings = self.mod.getBuildingById(fields=[
            'BuildingId', 'BuildingType', 'CompleteTime', 'LastOptType'
        ],
                                                TimeStamp=TimeStamp)
        IsOwner = False  #建筑是不是玩家的
        HomeLevel = 0  #将军府等级
        for Building in AllBuildings:
            if Building['BuildingId'] == BuildingId:
                BuildingLevel = Building["BuildingRealLevel"]
                BuildingType = Building["BuildingType"]
                BuildingState = Building['BuildingState']
                IsOwner = True
                #print '完成时间', Building['CompleteTime']
            if Building['BuildingType'] == 1:  #将军府的BuildingType是1
                HomeLevel = Building['BuildingRealLevel']

        if not IsOwner:
            return Gcore.error(optId, -15002001)  #用户没有该建筑
        if BuildingState:
            return Gcore.error(optId, -15002002)  #不是空闲状态的建筑,无法升级。

        BuildingCfg = Gcore.getCfg('tb_cfg_building', BuildingType)
        BuildingUpCfg = Gcore.getCfg('tb_cfg_building_up',
                                     (BuildingType, BuildingLevel + 1))

        MaxLevel = BuildingCfg['MaxLevel']
        MaxLevelHomeDif = BuildingCfg['MaxLevelHomeDif']

        if BuildingLevel >= MaxLevel:
            return Gcore.error(optId, -15002003)  #建筑已达最高等级

        if BuildingType != 1 and BuildingLevel - HomeLevel >= MaxLevelHomeDif:
            return Gcore.error(optId, -15002004)  #建筑与将军府的差应该小于MaxLevelHomeDif

        AllWorkerNum = self.mod.getWorkerNum()
        BusyWorkerNum = len([
            Building for Building in AllBuildings
            if Building['BuildingState'] != 0
        ])
        FreeWorkerNum = AllWorkerNum - BusyWorkerNum
        if FreeWorkerNum <= 0:
            return Gcore.error(optId, -15002904)  #建筑工匠数量不足

        CoinType = BuildingCfg['CoinType']
        CoinNum = BuildingUpCfg['CostValue']
        CDValue = BuildingUpCfg['CDValue']

        #print '不受内政影响的CD', CDValue
        #print 'min', CDValue/60, 'sec', CDValue%60

        #建筑CD时间受内政4影响, 花费受内政7影响 by Lizr 130611
        interMod = Gcore.getMod('Inter', self.uid)
        CDValue = interMod.getInterEffect(4, CDValue)
        CoinNum = interMod.getInterEffect(7, CoinNum)

        #print 'cd', CDValue
        #print 'min', CDValue/60, 'sec', CDValue%60
        #print '完成时间', TimeStamp + CDValue

        #开始支付
        modCoin = Gcore.getMod('Coin', self.uid)
        classMethod = '%s.%s' % (self.__class__.__name__,
                                 sys._getframe().f_code.co_name)
        pay = modCoin.PayCoin(optId, CoinType, CoinNum, classMethod, param)
        if pay < 0:
            return Gcore.error(optId, -15002995, {
                'CoinNum': CoinNum,
                'RestCoin': modCoin.getCoinNum(CoinType)
            })  #支付失败

        UpInfo = {}
        UpInfo['CoinType'] = CoinType
        UpInfo['BuildingPrice'] = CoinNum
        UpInfo['LastChangedTime'] = TimeStamp
        UpInfo['CompleteTime'] = TimeStamp + CDValue
        UpInfo['BuildingLevel'] = BuildingLevel + 1
        UpInfo['LastOptType'] = 1
        stat = self.mod.updateBuildingById(UpInfo, BuildingId)
        if not stat:
            return Gcore.error(optId, -15002997)  #系统错误
        print '建筑升级完成', time.time() - starttime
        #不同类型的建筑进行不同的运算
        # + todo
        if BuildingType == 2 or BuildingType == 5:  #磨坊,铸币厂升级收集军资
            print '建筑升级计算资源'
            starttime = time.time()
            ColInfo = Gcore.getMod('Building_resource',
                                   self.uid).collectCoin(optId,
                                                         BuildingType,
                                                         BuildingId,
                                                         TimeStamp,
                                                         param=param)
            CoinType = 2 if BuildingType == 2 else 3
            body['NowCoin'] = ColInfo.get('NowCoin')
            body['Remain'] = ColInfo.get('Remain')
            body['CoinType'] = CoinType
            print '建筑升级计算资源', time.time() - starttime

        if BuildingType in (6, 8):  #兵营 工坊:计算士兵
            print '建筑升级计算士兵'
            starttime = time.time()

            modCamp = Gcore.getMod('Building_camp', self.uid)
            modCamp.TouchAllSoldiers(TimeStamp=TimeStamp)
            if BuildingType in (6, 8):  #兵营 工坊 升级时暂停
                update_dic = {
                    'LastChangedTime': TimeStamp + CDValue,
                    'BuildingLevel': BuildingLevel + 1
                }
                modCamp.updateProcessById(update_dic, BuildingId)

            print '建筑升级计算士兵', time.time() - starttime
        if BuildingType == 18:  #点将台
            print '建筑升级-点将台'
            starttime = time.time()
            modTrain = Gcore.getMod('Building_train', self.uid)
            Buildings = [
                building for building in AllBuildings
                if building['BuildingType'] == BuildingType
            ]
            #print 'Buildings', Buildings
            modTrain.normalAddTrainNum(num=0,
                                       TimeStamp=TimeStamp,
                                       Buildings=Buildings)
            print '建筑升级-点将台', time.time() - starttime
        #成功
        print '查询金钱'
        starttime = time.time()
        body['Coin%s' % CoinType] = modCoin.getCoinNum(CoinType)
        print '查询金钱', time.time() - starttime

        recordData = {
            'uid': self.uid,
            'ValType': BuildingType,
            'Val': 1
        }  #成就、任务记录
        if Gcore.TEST:
            body['test'] = {'payCoin': pay, 'Currency': modCoin.getCurrency()}

        return Gcore.out(optId, body, mission=recordData)
Ejemplo n.º 43
0
    def getDefenseGeneral(self, UserId=None):
        '''获取布防上场的武将'''
        if not UserId:
            UserId = self.uid
        kLeader = Gcore.loadCfg(Gcore.defined.CFG_BATTLE)["kLeaderAddNum"]
        SoldierTechs = Gcore.getMod('Book', UserId).getTechsLevel(1)

        DenfeseGenerals = self.db.out_rows('tb_wall_general',
                                           ['GeneralId', 'x', 'y'],
                                           "UserId=%s" % UserId)
        if not DenfeseGenerals:
            return {}
        dictDG = {}
        for r in DenfeseGenerals:
            dictDG[r.get('GeneralId')] = r

        GeneralIds = [int(row['GeneralId']) for row in DenfeseGenerals]
        fields = [
            'GeneralId', 'GeneralType', 'GeneralLevel', 'ForceValue',
            'WitValue', 'SpeedValue', 'LeaderValue', 'TakeType',
            'TakeTypeDefense'
        ]

        GeneralInfo = {}
        Grows = Gcore.getMod('General',
                             UserId).getGeneralInfo(GeneralIds, fields)
        for row in Grows:
            if not row['TakeTypeDefense']:
                if Gcore.getCfg('tb_cfg_soldier', row['TakeType'],
                                'SoldierSide') == 4:
                    row['TakeTypeDefense'] = 0
                else:
                    row['TakeTypeDefense'] = row['TakeType']
            else:
                if Gcore.getCfg('tb_cfg_soldier', row['TakeTypeDefense'],
                                'SoldierSide') == 4:
                    row['TakeTypeDefense'] = 0

            row['Skill'] = Gcore.getCfg('tb_cfg_general', row['GeneralType'],
                                        'SkillId')
            SoldierType = row['TakeTypeDefense'] if row[
                'TakeTypeDefense'] else 1
            SoldierLevel = SoldierTechs.get(SoldierType)
            SoldierNum = row['LeaderValue'] * kLeader

            row['SoldierType'] = SoldierType
            row['SoldierLevel'] = SoldierLevel
            key = (SoldierType, SoldierLevel)
            cfg_soldier = Gcore.getCfg('tb_cfg_soldier_up', key)

            #            row['Life'] = cfg_soldier['Life']*row['LeaderValue']*kLeader
            #            row['Attack'] = cfg_soldier['Attack']*row['LeaderValue']*kLeader
            #            row['Denfense'] = cfg_soldier['Defense']

            row['Life'] = F.getArmyLife(cfg_soldier['Life'], SoldierNum)
            row['Attack'] = F.getArmyAttack(
                generalType=row['GeneralType'],
                soldierType=row['SoldierType'],
                landForm=4,
                soldierAttack=cfg_soldier['Attack'],
                soldierNum=SoldierNum,
                forceValue=row['ForceValue'],
            )
            row['Denfense'] = F.defenseAdd(cfg_soldier['Defense'],
                                           row['SpeedValue'],
                                           row['GeneralType'])

            #            del row['ForceValue']
            #            del row['WitValue']
            #            del row['SpeedValue']
            #            del row['LeaderValue']

            del row['TakeType']
            del row['TakeTypeDefense']

            row['x'] = dictDG.get(row['GeneralId']).get('x')
            row['y'] = dictDG.get(row['GeneralId']).get('y')

            GeneralInfo[row['GeneralId']] = row

        return GeneralInfo
Ejemplo n.º 44
0
    def getWallGeneralList(self):
        '''获取布防武将列表  参考getWallGeneralList()  
        @call: WallUI
        @author: by Lizr
        '''
        kLeader = Gcore.loadCfg(Gcore.defined.CFG_BATTLE)["kLeaderAddNum"]
        SoldierTechs = Gcore.getMod('Book', self.uid).getTechsLevel(1)

        InListGeneral = self.db.out_list('tb_wall_general', 'GeneralId',
                                         "UserId=%s" % self.uid)  #已布防

        fields = [
            'GeneralId', 'GeneralType', 'GeneralLevel', 'ForceValue',
            'WitValue', 'SpeedValue', 'LeaderValue', 'TakeType',
            'TakeTypeDefense'
        ]
        rows = Gcore.getMod('General', self.uid).getMyGenerals(fields)
        #Gcore.printd( rows )
        GeneralList = []
        for row in rows:
            if not row['TakeTypeDefense']:
                row['TakeTypeDefense'] = row['TakeType']

            row['Skill'] = Gcore.getCfg('tb_cfg_general', row['GeneralType'],
                                        'SkillId')
            SoldierType = row['TakeTypeDefense']
            SoldierLevel = SoldierTechs.get(SoldierType)
            row['SoldierType'] = SoldierType
            row['SoldierLevel'] = SoldierLevel
            key = (SoldierType, SoldierLevel)
            SoldierNum = row['LeaderValue'] * kLeader

            cfg_soldier = Gcore.getCfg('tb_cfg_soldier_up', key)
            if cfg_soldier:
                #row['Life'] = cfg_soldier['Life']* row['LeaderValue']*kLeader
                #row['Attack'] = cfg_soldier['Attack']*row['LeaderValue']*kLeader
                #row['Denfense'] = cfg_soldier['Defense']

                row['Life'] = F.getArmyLife(cfg_soldier['Life'], SoldierNum)
                row['Attack'] = F.getArmyAttack(
                    generalType=row['GeneralType'],
                    soldierType=row['SoldierType'],
                    landForm=4,
                    soldierAttack=cfg_soldier['Attack'],
                    soldierNum=SoldierNum,
                    forceValue=row['ForceValue'],
                )
                row['Denfense'] = F.defenseAdd(cfg_soldier['Defense'],
                                               row['SpeedValue'],
                                               row['GeneralType'])
            else:
                row['Life'] = 0
                row['Attack'] = 0
                row['Denfense'] = 0

            row['InWall'] = row['GeneralId'] in InListGeneral  #是否在布防中

            #            del row['ForceValue']
            #            del row['WitValue']
            #            del row['SpeedValue']
            #            del row['LeaderValue']

            del row['TakeType']
            del row['TakeTypeDefense']

            GeneralList.append(row)
        return GeneralList
Ejemplo n.º 45
0
                                                  {'lockstate': 0},
                                                  "id=%s" % row['id'])  #解锁
                    except Exception, e:
                        print e
                        pass
                    finally:
                        db.close()
                if dic['method'] == 'hset':
                    Redis.hset(self, dic['h'], dic['k'], dic['v'])
                elif dic['method'] == 'set':
                    Redis.set(self, dic['k'], dic['v'])
                    #print 'Redis.set',dic['k'],dic['v']
                delay = 0
            except:
                #将队列插入数据库
                db = Gcore.getNewDB()
                dic['CreateTime'] = Gcore.common.nowtime()
                result = db.insert('tb_delay_redis', dic)
                #print db.sql
                if not result:
                    self._queue.put(buff)  #如果插不进去 再加回队列中
                    gevent.sleep(10)  #等待数据库恢复
                db.close()
                delay = 1

    def set(self, k, v):
        print '%s.set' % self.sign, k, v
        dic = {'method': 'set', 'k': k, 'v': v}
        buff = json.dumps(dic)
        self.put(buff)
Ejemplo n.º 46
0
                    incdic.get(row["UserId"], {}).get(1, 0) + row["Jcoin"])
                gstr += ' WHEN %d THEN %d' % (
                    row["UserId"],
                    incdic.get(row["UserId"], {}).get(2, 0) + row["Gcoin"])
            jstr += ' END '
            gstr += ' END '
            sql = 'UPDATE tb_hold_log SET Jcoin=%s, Gcoin=%s, LastGiveTime="%s" WHERE %s' \
                    % (jstr, gstr, curtime, where)
            pyDB.execute(sql)

    #自动解除关系
    for row in rows:
        if row["HoldEndTime"] > curtime:
            continue
        if row["HolderServerId"] == config.SERVER_ID:  #本服
            ui = Gcore.getUI('Building_hold', row["HolderId"])
            ui.SlaveOperand({
                'typ': 2,
                'uid': row["UserId"],
                'sid': config.SERVER_ID
            })
        else:  #非本服,发消息
            try:
                msg = {
                    'HolderId': row["HolderId"],
                    "GiverId": row["UserId"],
                    "GiverServerId": config.SERVER_ID
                }
                msg['optId'] = 3
                msg = str(msg)
                message = amqp.Message(msg)
Ejemplo n.º 47
0
    def EquipStrengthen(self,p={}):
        '''强化装备'''
        optId = 16001
        equipId = p['EquipId']
        generalId = p['GeneralId']
        building = self.mod.getSmithyInfo()
        if not building:
            return Gcore.error(optId,-16001901)#建筑不存在
        buildingId = building['BuildingId']
        equipInfo = self.mod.getEquipInfo(1,equipId)#装备信息
        if not equipInfo or equipInfo['UserId'] != self.uid:
            return Gcore.error(optId,-16001910)#装备不存在
        generalMod = Gcore.getMod('General',self.uid)
        generalInfo = generalMod.getLatestGeneralInfo(GeneralIds=generalId)
        
        if not generalInfo:
            return Gcore.error(optId,-16001001) #武将不存在
        if equipId not in self.mod.getEquipsByGeneral(generalId).values():
            return Gcore.error(optId,-16001004)#武器不在该武将身上
        
        equipType = equipInfo['EquipType']
        equipCfg = Gcore.getCfg('tb_cfg_equip',equipType)#装备配置
        strengthenLimit =  equipCfg.get('StrengthenLimit')
        equipPart = equipCfg.get('EquipPart')
        
        equipLevel = equipInfo.get('StrengthenLevel')
        generalLevel = generalInfo.get('GeneralLevel')
        free = self.mod.getMaxStrength(buildingId)['Available']
        if free == 0:
            return Gcore.error(optId,-16001002)#强化次数不足
        elif equipLevel >= generalLevel or equipLevel>= strengthenLimit:
            return Gcore.error(optId,-16001003)#已达最大等级
        
        equipUpCfg = Gcore.getCfg('tb_cfg_equip_up',(equipLevel+1,equipPart))#装备强化配置
        costType = equipUpCfg.get('StrengthenCostType')
        cost = equipUpCfg.get('CostQuality%s'%equipCfg.get('Quality'))
#         print '==Pre:',cost
        
        #计算内政对强化花费的影响
        interMod = Gcore.getMod('Inter',self.uid)
        cost = interMod.getInterEffect(8,cost)
#         print '===Reday:',cost
        flag = self.coinMod.PayCoin(optId,costType,cost,'EquipUI.EquipStrengthen',p)
        if flag>0:
            strengthData = {'StrengthenLevel':equipLevel+1,
                            'EnhanceForce':equipInfo['EnhanceForce']+equipCfg['GrowForce'],
                            'EnhanceWit':equipInfo['EnhanceWit']+equipCfg['GrowWit'],
                            'EnhanceSpeed':equipInfo['EnhanceSpeed']+equipCfg['GrowSpeed'],
                            'EnhanceLeader':equipInfo['EnhanceLeader']+equipCfg['GrowLeader']
                            }
            self.mod.equipStrengthen(buildingId, equipId,equipType,strengthData)
            generalMod.changeAttr(generalId,equipCfg['GrowForce'],equipCfg['GrowSpeed'],equipCfg['GrowWit'],equipCfg['GrowLeader'])
            recordData = {'uid':self.uid,'ValType':0,'Val':1,'EquipType':equipType,'EquipLevel':equipLevel+1}#成就、任务记录
            return Gcore.out(optId,achieve=recordData,mission=recordData)
        else:
            return Gcore.error(optId,-16001995) #支付失败 
Ejemplo n.º 48
0
    def HighEquipStrengthen(self,p={}):
        '''兵书宝物升级'''
        optId = 16007
        goodsType = p['UPT']
        equipId = p['EID']
        offerIds = p['OFS']
        
        if (not isinstance(offerIds,(list,tuple))) or (goodsType not in (4,5)) or (not offerIds) or(equipId in offerIds):
            return Gcore.error(optId,-16007999)
        cfgEquipTable = self.mod.getCfgEquipTB(goodsType)
        
        equipInfo = self.mod.getEquipByIds(goodsType,equipId)
        if not equipInfo:
            return Gcore.error(optId,-16007001)#装备不存在

        generalId = equipInfo['GeneralId']

        generalInfo = Gcore.getMod('General',self.uid).getLatestGeneralInfo(GeneralIds=generalId)
        if not generalId or not generalInfo:
            return Gcore.error(optId,-16007002)#须让武将戴上才能升级
        
        equipLevel = equipInfo.get('StrengthenLevel')
        generalLevel = generalInfo.get('GeneralLevel')
        
        equipCfgs = Gcore.getCfg(cfgEquipTable)
        equipUpCfgs = Gcore.getCfg(cfgEquipTable+'_up')
        
        equipType = equipInfo.get('EquipType')
        equipCfg = equipCfgs.get(equipType)
        strengthenLimit = equipCfg['StrengthenLimit']
        if equipLevel>= generalLevel or equipLevel>=strengthenLimit:
            return Gcore.error(optId,-16007003)#已达最大等级
        
        #计算升级消耗货币,增加的经验
        offers = self.mod.getEquipByIds(goodsType,offerIds)#返回列表
        strengthenCostType = equipCfg['NeedCostType']
        deleteIds = []
        strengthCost = 0
        strengthGetExp = 0
        
        for offer in offers:
            deleteIds.append(offer['EquipId'])
            offerType = offer.get('EquipType')
            offerCfg = equipCfgs.get(offerType)
            offerUpCfg = equipUpCfgs.get(offer.get('StrengthenLevel'))
            
            baseExp = offerCfg['BaseExp']
            offerQuality = offerCfg['Quality']
            strengthGetExp = strengthGetExp+baseExp+offerUpCfg['Offer%s'%offerQuality]
            strengthCost += offerCfg['NeedCost']
        #判断是否爆击
        exploded = 0 #是否爆击
        explodeRatio = Gcore.loadCfg(Gcore.defined.CFG_EQUIP)['ExplodeRatio'][str(goodsType)]
        explodeTimes = Gcore.loadCfg(Gcore.defined.CFG_EQUIP)['ExplodeTimes'][str(goodsType)]
        if random.randint(1,100)<=explodeRatio:
            strengthGetExp = strengthGetExp*explodeTimes
            exploded = 1 
        
        payState = self.coinMod.PayCoin(optId,strengthenCostType,strengthCost,'EquipUI.HighEquipStrengthen',p)
        if payState>0:
            newLevel,newExp = self.mod.highEquipStengthen(goodsType,equipId,strengthGetExp)
            Gcore.getMod('Bag',self.uid).deleteEquips(goodsType,deleteIds)
            return Gcore.out(optId,{'NL':newLevel,'EXP':newExp,'EXPD':exploded})
        elif payState==-2:
            return Gcore.error(optId,-16007994)#货币不足
        else:
            return Gcore.error(optId,-16007995)#支付失败
Ejemplo n.º 49
0
    def SaleEquip(self,p={}):
        '''出售装备或道具'''
        optId = 16004

        goodsNum = p.get('GoodsNum',1)
        position = p['Position']

        building = self.mod.getSmithyInfo()
        if building is None:
            return Gcore.error(optId,-16004901)#建筑不存在
        modBag=Gcore.getMod('Bag',self.uid)
        gInfo = modBag.getFromPosition(position)
        if not gInfo:
            return Gcore.error(optId,-16004001)#物品不在背包中
        goodsType = gInfo['GoodsType']
        goodsId = gInfo['GoodsId']
        keepNum = gInfo['GoodsNum']
        if keepNum<goodsNum:
            return Gcore.error(optId,-16004002)#物品出售数量有误
        
        #计算当前可用
        buildingMod = Gcore.getMod('Building',self.uid)
        maxSave = buildingMod.cacStorageSpace(3)#最大储量
        curSave = self.coinMod.getCoinNum(3)#当前数量
        leftSave = maxSave-curSave

        flag = 0
        #出售流程
        if goodsType in (1,4,5):#出售装备
            equipInfo = self.mod.getEquipInfo(goodsType,goodsId)
            if not equipInfo:
                return Gcore.error(optId,-16004006)#装备不属于你

            cost = self.mod.calSalePrice(goodsType,equipInfo['EquipType'],equipInfo['StrengthenLevel'])
            if cost<=leftSave:
                flag = modBag.moveEquip(remove=goodsId,goodsType=goodsType)
            else:
                
                return Gcore.error(optId,-16004004)#没有足够空间存放货币
            
        else:#出售道具
            itemCfg = Gcore.getCfg('tb_cfg_item',goodsId)
            saled = itemCfg['SaleOrNot']
            if saled != 1:
                return Gcore.error(optId,-16004003)#该道具不可售
            cost = itemCfg['PriceInShop']
            cost = cost*goodsNum
            
            if cost<=leftSave:
                flag = modBag.useItems(goodsType,goodsNum,position)
            else:
                return Gcore.error(optId,-16004004)#没有足够空间存放货币
        
        #获得货币流程
        if flag:
            self.coinMod.GainCoin(optId,3,cost,'EquipUI.SaleEquip',p)
            self.mod.saleGoods(goodsType,goodsId,goodsNum)
            
            recordData = {'uid':self.uid,'ValType':goodsType,'Val':goodsNum,'GoodsId':goodsId}#成就、任务记录 
            return Gcore.out(optId,{'Cost':cost},mission=recordData)
        else:
            return Gcore.error(optId,-16004005)#出售失败
Ejemplo n.º 50
0
 def DivertEquip(self,p={}):
     '''装备传承'''
     optId = 16006
     fromId = p['From']
     toId = p['To']
     fromEquip = self.mod.getEquipInfo(1,fromId)
     toEquip = self.mod.getEquipInfo(1,toId)
     
     if not fromEquip or not toEquip:
         return Gcore.error(optId,-16006999)#参数无效
     
     if (fromEquip['EquipStatus'] not in (1,2)) or (toEquip['EquipStatus'] not in (1,2)):
         return Gcore.error(optId,-16006001)#装备不存在
     fromLevel = fromEquip.get('StrengthenLevel')
     toLevel = toEquip.get('StrengthenLevel')
     fromType = fromEquip.get('EquipType')
     toType = toEquip.get('EquipType')
     fromCfg = Gcore.getCfg('tb_cfg_equip',fromType)
     toCfg = Gcore.getCfg('tb_cfg_equip',toType)
     toMaxLevel = toCfg.get('StrengthenLimit')
     
     if fromLevel<1:
         return Gcore.error(optId,-16006002)#源装备等级大于0
     if toLevel>=toMaxLevel:
         return Gcore.error(optId,-16006003)#目标装备等级已达最大
     
     equipUpCfg = Gcore.getCfg('tb_cfg_equip_up')
     
     #判断目标装备是否穿戴在武将身上,升级受武将等级限制
     toGeneralId = toEquip.get('GeneralId')
     generalInfo = Gcore.getMod('General',self.uid).getLatestGeneralInfo(GeneralIds=toGeneralId)
     generalLevel = generalInfo['GeneralLevel'] if (toGeneralId and generalInfo) else 9999
     
     #计算源装备强化总强化费用
     fromCost = 0
     fromPart = fromCfg['EquipPart']
     fromQuality = fromCfg['Quality']
     for i in range(1,fromLevel+1):
         fromCost += equipUpCfg[(i,fromPart)]['CostQuality%s'%fromQuality]
     
     
     #计算传承后等级
     toLevelUp,leftCost = self._calLevelByCost(toType,toLevel,fromCost,min(toMaxLevel,generalLevel)) 
     fromLevelDown = self._calLevelByCost(fromType,0,leftCost)[0]
     
     fromData = {'EnhanceForce':fromCfg['AddForce']+fromCfg['GrowForce']*fromLevelDown,
                 'EnhanceLeader':fromCfg['AddLeader']+fromCfg['GrowLeader']*fromLevelDown,
                 'EnhanceSpeed':fromCfg['AddSpeed']+fromCfg['GrowSpeed']*fromLevelDown,
                 'EnhanceWit':fromCfg['AddWit']+fromCfg['GrowWit']*fromLevelDown,
                 'StrengthenLevel':fromLevelDown
                 }
     toData = {'EnhanceForce':toCfg['AddForce']+toCfg['GrowForce']*toLevelUp,
                 'EnhanceLeader':toCfg['AddLeader']+toCfg['GrowLeader']*toLevelUp,
                 'EnhanceSpeed':toCfg['AddSpeed']+toCfg['GrowSpeed']*toLevelUp,
                 'EnhanceWit':toCfg['AddWit']+toCfg['GrowWit']*toLevelUp,
                 'StrengthenLevel':toLevelUp
                 }
     divertCost = Gcore.loadCfg(Gcore.defined.CFG_EQUIP).get('DivertCost')
     divertCostType = Gcore.loadCfg(Gcore.defined.CFG_EQUIP).get('DivertCostType')
     payState = self.coinMod.PayCoin(optId,divertCostType,divertCost,'EquipUI.DivertEquip',p)
     if payState:
         self.mod.updateEquipInfo(1,fromData,'UserId=%s AND EquipId=%s'%(self.uid,fromId))
         self.mod.updateEquipInfo(1,toData,'UserId=%s AND EquipId=%s'%(self.uid,toId))
         return Gcore.out(optId,{'FromInfo':fromData,'ToInfo':toData,'Cost':payState})
     elif payState==-2:
         return Gcore.error(optId,-16006994)#货币不足
     else:
         return Gcore.error(optId,-16006995)#支付失败
Ejemplo n.º 51
0
 def __init__(self, uid):
     '''注释'''
     Base.__init__(self, uid)
     self.uid = uid
     self.cfgRank = Gcore.loadCfg(Gcore.defined.CFG_RANK_FIGHT)
Ejemplo n.º 52
0
 def __init__(self,uid = 0):
     self.uid = uid
     self.mod = Gcore.getMod('Equip',uid)
     self.coinMod = Gcore.getMod('Coin',uid)
Ejemplo n.º 53
0
 def CheckGeneralSoldier(self, param={}):
     '''检查是否有武将上场和兵 by Lizr'''
     optId = 15127
     CanFight = Gcore.getMod('Battle', self.uid)._checkGeneralSoldier()
     return Gcore.out(optId, body={'CanFight': CanFight})
Ejemplo n.º 54
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
Ejemplo n.º 55
0
    def getSoldierStorage(self,
                          building_info,
                          time_stamp,
                          set_cal_time=None,
                          is_sync=False,
                          add_num=0):
        '''获取新兵数量'''
        #is_sync - 是否将更新写回数据库
        #set_cal_time - 设置兵营的最近征兵时间,如不设置则为time_stamp
        cal_interval = 300  #计算时间间隔
        time_stamp = int(time_stamp)

        building_level = building_info['BuildingRealLevel']
        building_type = building_info['BuildingType']
        building_id = building_info['BuildingId']
        last_opt_type = building_info['LastOptType']
        complete_time = building_info['CompleteTime']

        if last_opt_type == 0 and complete_time > time_stamp:
            print 'complete_time', complete_time
            print 'time_stamp', time_stamp
            return {}  #兵营或工坊还未建造完成

        camp_record = self.db.out_fields(
            self._soldier_storage, '*',
            'UserId=%s AND BuildingId=%s' % (self.uid, building_id))

        if not camp_record:  #士兵生产表中没有该建筑的信息,插入一条初始记录
            camp_record = self.initRecord(building_id, building_type,
                                          time_stamp, building_level,
                                          complete_time)
        if time_stamp <= camp_record['LastCalTime']:
            return camp_record  #本次计算时间太小

        if camp_record[
                'LastCalTime'] < complete_time <= time_stamp and last_opt_type == 1:
            add_num += Gcore.getCfg('tb_cfg_building_up',
                                    (building_type, building_level),
                                    'MakeValue') - \
                        Gcore.getCfg('tb_cfg_building_up',
                                     (building_type, building_level-1),
                                     'MakeValue')

        camp_record['LastCalTime'] = time_stamp
        camp_cfg = Gcore.getCfg('tb_cfg_building_up',
                                (building_type, building_level))
        speed = camp_cfg['HourValue']
        make_value = camp_cfg['MakeValue']

        storage_num = camp_record['StorageNum']
        last_changed_time = camp_record['LastChangedTime']
        if last_changed_time >= time_stamp or last_changed_time + cal_interval > time_stamp:
            print '未到计算时间'
            if add_num:
                camp_record['StorageNum'] = min(storage_num + add_num,
                                                make_value)
            if set_cal_time: camp_record['LastChangedTime'] = set_cal_time
            if add_num or set_cal_time:
                self.db.update(
                    self._soldier_storage, camp_record,
                    'UserId=%s AND BuildingId=%s' % (self.uid, building_id))
            return camp_record

        print '过去了', (time_stamp -
                      last_changed_time) // cal_interval, '个计算时间间隔'
        print '生产速度', speed // 3600, '每秒'
        new_add_num = ((time_stamp - last_changed_time) //
                       cal_interval) * cal_interval * (speed // 3600)
        print '理论生产', new_add_num
        print '已有', storage_num
        print '征兵上限', make_value

        camp_record['StorageNum'] = min(storage_num + new_add_num + add_num,
                                        make_value)  #新兵数量
        camp_record['LastChangedTime'] = ((time_stamp) - (time_stamp-last_changed_time)%cal_interval) \
                                if not set_cal_time else set_cal_time

        if is_sync or add_num:
            print '将士兵生产信息写回数据库'
            self.db.update(
                self._soldier_storage, camp_record,
                'UserId=%s AND BuildingId=%s' % (self.uid, building_id))
        else:
            print '不将士兵生产信息写回数据库'
        return camp_record
Ejemplo n.º 56
0
    def SetHold(self, param={}):
        '''设置藩国'''
        optId = 15122

        BuildingId = param.get('BuildingId')  #建筑ID
        if not BuildingId:
            BuildingId = Gcore.getMod(
                'Building', self.uid).getBuildingIdByType(10)  #by Lizr

        suid = param['SlaveUID']  #奴隶ID
        ssid = param['SlaveSID']  #奴隶服务器ID
        ts = param['ClientTime']  #时间戳

        #if self.mod.getHolder(self.uid, Gcore.getServerId(), False) is not None:
        #    return Gcore.error(optId, -15122001) #玩家本身不是自由身 -> 改为不是自由身也可以设为别人为藩国

        if self.mod.getHolder(suid, ssid, False) is not None:
            return Gcore.error(optId, -15122002)  #要设置的玩家不是自由身

        #是否是我的手下败将
        MyDefeaters = self.mod.getDefeaters()
        if not (suid, ssid) in [(d["PeerUID"], d["PeerSID"])
                                for d in MyDefeaters]:
            return Gcore.error(optId, -15122003)  #不是手下败将

        #藩国最大数量
        modBuilding = Gcore.getMod('Building', self.uid)
        BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=ts)
        #print 'BuildingId',BuildingId
        #print 'BuildingInfo',type(BuildingInfo),BuildingInfo
        if not BuildingInfo:
            return Gcore.error(optId, -15122004)  #玩家没有这个理藩院
        if BuildingInfo['BuildingState'] == 1:
            return Gcore.error(optId, -15122005)  #建筑正在建造
        if BuildingInfo['BuildingType'] != 10:
            return Gcore.error(optId, -15122006)  #建筑不是理藩院
        MaxNum = Gcore.getCfg('tb_cfg_building_up',
                              (10, BuildingInfo['BuildingRealLevel']),
                              'SaveValue')

        if len(self.mod.getHold()) >= MaxNum:
            return Gcore.error(optId, -15122007)  #藩国数量已达最大
        hsid, huid = self.mod.getMyHolder()

        if hsid == ssid and huid == suid:
            return Gcore.error(optId, -15122009)  #不能设自己的主人为藩国

        stat = self.mod.setHold(suid, ssid)
        if stat == -1:
            return Gcore.error(optId, -15122010)  #玩家处于调停中,无法设为潘国
        elif stat < 0:
            return Gcore.error(optId, -15122008)  #设置藩国失败

        #从手下败将中删除
        self.mod.delDefeater(suid, ssid)

        #被设为藩国也不释放自己的藩国
        ''' # 释放掉藩国的所有藩国, 如果是本服,调用本服接口
        if ssid == Gcore.getServerId():
            ui = Gcore.getUI('Building_hold', suid)
            print dir(ui)
            print ui.uid
            mod = Gcore.getMod('Building_hold', suid)
            print '奴隶的奴隶', mod.getHold()
            for h in mod.getHold():
                ui.SlaveOperand({'typ':2, 'uid':h["UserId"],
                                 'sid':h.get("ServerId", ssid)})
        '''
        recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1}  #任务
        return Gcore.out(optId,
                         body={},
                         mission=recordData,
                         achieve=recordData)
Ejemplo n.º 57
0
 def reload_server():
     Gcore.reload()
     logger.warning('I got a signal.SIGUSR2, Gcore reload()')
Ejemplo n.º 58
0
 def __init__(self, uid):
     self.mod = Gcore.getMod("Building_hold", uid)
     self.uid = uid
Ejemplo n.º 59
0
         pass
     
     strExcept = ' >> '+str(e)
     response = False
 finally:
     try: #调试日志
         optInfo = {
            93001:'createWar',
            93001:'findSiege',
            93002:'startSiege',
            93003:'leftSiege',
            93009:'endBattle',
            }
         if uid and optId and optId!=93004:
             runtime = time.time() - startTime
             db = Gcore.getNewDB()
             row = {
                      'UserId':uid,
                      'OptId':optId,
                      'CallMethod':optInfo.get(optId,'--'),
                      'Param':Gcore.common.json_encode(para),
                      'Response':Gcore.common.json_encode(response),
                      'Runtime':runtime,
                      'RecordTime':Gcore.common.datetime(),
                      }
             print row
             db.insert('temp_runtime_log', row, isdelay=True)
     except Exception,e:
         print 'Exception in battleway',e
     
 if type(response) is not dict and response is False: #None就是不返回
Ejemplo n.º 60
0
 def checkOpt(self,ckey,optId,optKey,para):
     #print 'checkOpt',ckey,optId,optKey,para
     response = False
     strExcept = ''
     if optId == 888888:
         Gcore.reload()
         response = Gcore.out(optId,{'Result':'Reload Success!'})
         self.Send(ckey,response) 
         print 'Gcore.reload()'
     elif optId == 10001: #登录
         self.checkLogin(ckey,optId,optKey,para)
     else:
         startTime = time.time()
         
         try:
             uid = self.Clients[ckey]['uid']
             if uid==0:
                 #self.Clients[ckey]['Channel'].close() #关闭socket连接
                 response = Gcore.error(optId,-88888888) #未登录
                 
             elif optId>90000 and optId<=90999: #开始战役
                 if optId == 90001: #开启战斗
                     response = self.BM.createWar(uid,para) 
                 else:
                     response = self.BM.doBattle(uid, optId, para) #暂未使用
                     
             elif optId>91000 and optId<=91999: #战役信息(开始战役战斗前)
                 response = proManager.checkOpt(uid, optId, para)
                 
             elif optId>93000 and optId<=93999: #攻城
                 if optId == 93001: #攻城入口
                     response = self.BM.findSiege(uid,para) #para: {storyBattleId:1} 任务战斗id
                 elif optId == 93002: #开始攻城
                     response = self.BM.startSiege(uid,para) 
                 elif optId == 93003: #离开攻城
                     response = self.BM.leftSiege(uid,para) 
                 elif optId == 93004: #同步  PVE PVC PVG
                     response = self.BM.synBattle(uid,para) 
                 elif optId == 93009: #结束战斗
                     response = self.BM.endBattle(uid,para) 
                 else:
                     response = self.BM.doWBattle(uid, optId, para)
             elif optId>94000 and optId<=94999: #比武
                 if optId == 94001: #开启比武
                     response = self.BM.createRankFight(uid,para) 
             else:
                 response = Gcore.error(optId,-33333333) #协议号未定义 
         except Exception,e: #错误日志
             try:
                 import traceback
                 strExcept = traceback.format_exc()
                 print >>sys.stderr, 'Time:' + time.strftime('%Y-%m-%d %H:%M:%S') + '\n' \
                         + 'UserId:' + str(uid) + '\n' \
                         + 'OptId:' + str(optId) + '\n' \
                         + 'Para:' + str(para) + '\n' \
                         + strExcept
                 sys.stderr.flush()
             except:
                 pass
             
             strExcept = ' >> '+str(e)
             response = False
         finally: