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) #没有可回收的防御工事
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)
def BuyItemEquip(self, param={}): '''商城购买装备或道具''' optId = 20006 ieSaleId = param['IeSaleId'] ieSaleCfg = Gcore.getCfg('tb_cfg_shop_ie_sale', ieSaleId) if ieSaleCfg is None: return Gcore.error(optId, -20006001)#商品不存在 modCoin = Gcore.getMod('Coin', self.uid) modBag = Gcore.getMod('Bag', self.uid) if not modBag.inclueOrNot(ieSaleCfg['SaleType'], ieSaleCfg['GoodsId'], ieSaleCfg['OnceNum']): return Gcore.error(optId, -20006002)#背包空间不足 classMethod = '%s,%s'%(self.__class__.__name__,sys._getframe().f_code.co_name) res = modCoin.PayCoin(optId, 1, ieSaleCfg['Price'], classMethod, param) if res == -2: return Gcore.error(optId, -20006994)#货币不足 if res < 0: return Gcore.error(optId, -20006995)#支付失败或者非法操作 modBag = Gcore.getMod('Bag', self.uid) buyId = modBag.addGoods(ieSaleCfg['SaleType'], ieSaleCfg['GoodsId'], ieSaleCfg['OnceNum'], addLog=optId) recordData = {'uid': self.uid, 'ValType': ieSaleCfg['GoodsId'], 'Val': ieSaleCfg['OnceNum'], 'GoodsType': ieSaleCfg['SaleType']}#成就、任务记录 return Gcore.out(optId, {'Result': buyId}, mission = recordData)
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)
def GetSpawnNum(self, param={}): '''获取当前时刻,兵营或工坊的新兵数量''' optId = 15030 BuildingId = param['BuildingId'] TimeStamp = param['ClientTime'] modBuilding = Gcore.getMod('Building', self.uid) BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp) if not BuildingInfo: return Gcore.error(optId, -15030001) #玩家没有该建筑 if BuildingInfo['BuildingState'] == 1: return Gcore.error(optId, -15030002) #建筑正在建造 if BuildingInfo['BuildingType'] not in (6, 8): return Gcore.error(optId, -15030003) #建筑不是兵营或工坊 print '建筑ID', BuildingId print '建筑类型', BuildingInfo['BuildingType'] print '建筑等级', BuildingInfo['BuildingLevel'] modCamp = Gcore.getMod('Building_camp', self.uid) spawn_detail= modCamp.getSoldierStorage(BuildingInfo, TimeStamp) body = {} body['StorageNum'] = spawn_detail['StorageNum'] body['LastChangedTime'] = spawn_detail['LastChangedTime'] return Gcore.out(optId, body=body)
def openSoliders(self, time_stamp=None, reverse=False): '''按照顺序返回玩家已开放的兵种''' #reverse-False从低到高,True从高到低 modBuilding = Gcore.getMod('Building', self.uid) Buildings = modBuilding.getBuildingByType(6, TimeStamp=time_stamp) Buildings = [ building for building in Buildings if building['BuildingState'] != 1 ] if not Buildings: return [] max_level = max( [building['BuildingRealLevel'] for building in Buildings]) print 'max_level', max_level soldier_details = Gcore.getCfg('tb_cfg_soldier').values() soldiers = [ soldier_detail for soldier_detail in soldier_details if soldier_detail['OpenLevel'] <= max_level and soldier_detail['SoldierClass'] == 1 and ( soldier_detail['SoldierSide'] == 0 or soldier_detail['SoldierSide'] == self.getUserCamp()) ] soldiers = sorted(soldiers, key=lambda dic: dic['OpenLevel'], reverse=reverse) Techs = Gcore.getMod('Book', self.uid).getTechsLevel(1) return [{ soldier['SoldierType']: Techs.get(soldier['SoldierType']) } for soldier in soldiers]
def GetSpawnNum(self, param={}): '''获取当前时刻,兵营或工坊的新兵数量''' optId = 15030 BuildingId = param['BuildingId'] TimeStamp = param['ClientTime'] modBuilding = Gcore.getMod('Building', self.uid) BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp) if not BuildingInfo: return Gcore.error(optId, -15030001) #玩家没有该建筑 if BuildingInfo['BuildingState'] == 1: return Gcore.error(optId, -15030002) #建筑正在建造 if BuildingInfo['BuildingType'] not in (6, 8): return Gcore.error(optId, -15030003) #建筑不是兵营或工坊 print '建筑ID', BuildingId print '建筑类型', BuildingInfo['BuildingType'] print '建筑等级', BuildingInfo['BuildingLevel'] modCamp = Gcore.getMod('Building_camp', self.uid) spawn_detail = modCamp.getSoldierStorage(BuildingInfo, TimeStamp) body = {} body['StorageNum'] = spawn_detail['StorageNum'] body['LastChangedTime'] = spawn_detail['LastChangedTime'] return Gcore.out(optId, body=body)
def vipAddTotal(self, optId, goldNum): ''' :玩家充值黄金,增加玩家累积黄金,更新Vip等级 @param goldNum:增加的黄金数量 ''' userInfo = self.getUserInfo(['VipLevel','VipTotalPay']) curLevel = userInfo.get('VipLevel') curVipTotal = userInfo.get('VipTotalPay') totalPay = goldNum+curVipTotal levelCfg = Gcore.getCfg('tb_cfg_vip_up') levelUp = max([levelCfg[level]['VipLevel'] for level in levelCfg if totalPay>=levelCfg[level]['TotalPay']]) data = {'VipTotalPay':totalPay,'VipLevel':levelUp} self.db.update('tb_user',data,'UserId=%s'%self.uid) if levelUp>curLevel:#VIP升级 interMod = Gcore.getMod('Inter',self.uid) interMod.updateInterVip()#更新VIP内政加成 Gcore.setUserData(self.uid,{'VipLevel':levelUp}) #更新用户缓存 Lizr Gcore.push(107,self.uid,{'VipLevel':levelUp}) #推送给前端升级 Lizr if curVipTotal==0: #增加首冲奖励 Gcore.getMod('Activity',self.uid).insertGifts(1,0) #发送系统邮件 mailMod = Gcore.getMod('Mail', self.uid) mailMod.sendSystemMail(self.uid, [], optId, other=[goldNum,]) return levelUp
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)})
def CheckMissionStatus(self ,p={}): '''检查任务状态''' optId = 22005 self.mod.updateAllMissions() Gcore.getMod('Building_home',self.uid).updateAllAchieves() return Gcore.out(optId)
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)
def GetBaseInfo(self,param={}): optId = 13003 userId=param['UserId'] modPlay=Gcore.getMod('Player',userId) fileds=['NickName','UserLevel','VipLevel','UserIcon','UserHonour','UserCamp','UserExp'] result= modPlay.getUserBaseInfo(fileds) if result is None: return Gcore.error(optId,-13003001)#用户不存在 result['Rank']=modPlay.getHonRankNum(result) buildingClub = Gcore.getMod('Building_club',userId) cId=buildingClub.getUserClubId() clubInfo=buildingClub.getClubInfo(cId,'ClubName') if clubInfo: result['ClubName']=clubInfo['ClubName'] #获得军团名字 else: result['ClubName']='' general=Gcore.getMod('General', userId) generalNum=general.getMyGenerals('count(1) as gNum') result['GeneralNum']=generalNum[0]['gNum'] #获得武将个数 modFriend=Gcore.getMod('Friend',userId) buildingNum=modFriend.getBuildingCount(userId) result['BuildingNum']=buildingNum return Gcore.out(optId,result)
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)
def freed(self, huid, hsid): #玩家达到一定要求,被释放。 '''被释放 , 玩家使用调解卡时调用,释放自己 @param huid: 主人的用户ID @param hsid: 主人的服务器ID ''' if hsid == self.serverid: #占领者在本服 Data = Gcore.getMod('Building_resource',self.uid).collectAll() #将地里的资源以被占领的身份收集一次 Data['HoldEndTime'] = 0 Gcore.push(112, self.uid, Data,Type=0) #查出进贡的钱 row = self.db.out_fields('tb_hold', ["JcoinGive", "GcoinGive"],\ 'GiverId="%s" AND HolderId="%s"'%(self.uid, huid)) if row: ja, ga = row["JcoinGive"], row["GcoinGive"] modCoin = Gcore.getMod('Coin', huid) j = modCoin.GainCoin(0, 2, ja, 'Building_holdMod.freed', {'hsid':hsid, 'huid':huid}) g = modCoin.GainCoin(0, 3, ga, 'Building_holdMod.freed', {'hsid':hsid, 'huid':huid}) dic = {'HolderId':0,'HolderServerId':0,'HoldEndTime':0} self.db.update('tb_user', dic, 'UserId="%s"' % self.uid) self.db.execute('DELETE FROM `tb_hold` WHERE GiverId="%s" AND HolderId="%s"' % (self.uid, huid)) self.db.execute('DELETE FROM `tb_hold_log` WHERE UserId="%s"' % self.uid) self.db.execute('DELETE FROM `tb_hold_revenge` WHERE UserId="%s"' % self.uid) else: #占领者不在本服 Gcore.sendmq(3, hsid, {'HolderId':huid, 'GiverServerId':self.serverid, 'GiverId':self.uid}) #删除自己的藩国redis Gcore.redisM.hdel("sgHold", '%s.%s' % (self.serverid, self.uid)) return 1
def gainRankReward(self, optId=0): '''领取排名奖励''' row = self.db.out_fields('tb_rank_fight_last', 'RankId,Rewarded', 'UserId=%s' % self.uid) MyRewardRankId = row['RankId'] Rewarded = row['Rewarded'] gainRewardList = [] if Rewarded: return gainRewardList cfg_rank_reward = Gcore.getCfg('tb_cfg_rank_reward') affected = self.db.update('tb_rank_fight_last', {'Rewarded': 1}, 'Rewarded=0 AND UserId=%s' % self.uid) if affected: for k, v in cfg_rank_reward.iteritems(): if v['RankFrom'] <= MyRewardRankId and MyRewardRankId <= v[ 'RankTo']: for i in xrange(1, 6): field1 = 'RewardType%s' % i field2 = 'GoodsId%s' % i field3 = 'GoodsNum%s' % i if v[field1] and v[field2]: Gcore.getMod('Reward', self.uid).reward( optId, {}, v[field1], v[field2], v[field3]) gainRewardList.append({ 'RewardType': v[field1], 'GoodsId': v[field2], 'GoodsNum': v[field3] }) break return gainRewardList
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
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
def Exchange(self, para={}): '''货币兑换 by Lizr''' optId = 20001 CoinType = para['CoinType'] CoinValue = para['CoinValue'] if CoinType not in (2, 3): return Gcore.error(optId, -20001998) #非法操作 if type(CoinValue) not in (int, long) or CoinValue <= 0: return Gcore.error(optId, -20001998) #非法操作 storageSpace = Gcore.getMod('Building', self.uid).cacStorageSpace(CoinType) addPercent = CoinValue / storageSpace rateInfos = Gcore.getCfg('tb_cfg_shop_res_sale') rateInfoList = filter(lambda dic:dic['AddPercent'] <= addPercent and dic['CoinType'] == CoinType, rateInfos.values()) rateInfo = max(rateInfoList, key=lambda sale:sale['AddPercent']) rate = rateInfo['kPrice1'] * (storageSpace ** rateInfo['kPrice2']) GoldValue = int(math.ceil(CoinValue * rate)) # rate = Gcore.loadCfg(2001).get('exchange').get(str(CoinType)) # GoldValue = math.ceil(CoinValue/rate) modCoin = Gcore.getMod('Coin', self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) pay = modCoin.PayCoin(optId, 1, GoldValue, classMethod, para) if pay < 0: return Gcore.error(optId, -20001995) #支付失败 else: #GainValue = GoldValue*rate #GainValue = int(math.ceil(GoldValue / rate)) #result = modCoin.GainCoin(optId, CoinType, GainValue, classMethod, para) result = modCoin.GainCoin(optId, CoinType, CoinValue, classMethod, para) body = {"CoinType": CoinType, "CoinValue": CoinValue, "GoldUsed": pay} return Gcore.out(optId, body)
def BuyResource(self, param={}): '''商城购买资源''' optId = 20002 classMethod = '%s,%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) resSaleId = param['ResSaleId'] resSaleCfg = Gcore.getCfg('tb_cfg_shop_res_sale', resSaleId) coinType = resSaleCfg['CoinType'] percent = resSaleCfg['AddPercent'] buildingMod = Gcore.getMod('Building', self.uid) maxCoin = buildingMod.cacStorageSpace(coinType) modCoin = Gcore.getMod('Coin', self.uid) currCoinNum = modCoin.getCoinNum(coinType) if percent < 1: coinValue = maxCoin * percent #增加货币 elif percent == 1: coinValue = maxCoin - currCoinNum #增加货币 percent = coinValue / maxCoin #print 'percent', percent resSaleList = Gcore.getCfg('tb_cfg_shop_res_sale') resSaleList = filter( lambda dic: dic['AddPercent'] <= percent and dic['CoinType'] == coinType, resSaleList.values()) resSaleCfg = max(resSaleList, key=lambda sale: sale['AddPercent']) # print resSaleList # resSaleList.sort(key=lambda sale:sale['AddPercent']) # if resSaleList: # resSaleCfg=resSaleList.pop() else: return Gcore.error(optId, -20002001) #percent错误,大于1 if currCoinNum + coinValue > maxCoin: return Gcore.error(optId, -20002002) #超过资源上限 kPrice1 = resSaleCfg['kPrice1'] kPrice2 = resSaleCfg['kPrice2'] #支付黄金 useCoinValue = int(math.ceil(coinValue * kPrice1 * maxCoin**kPrice2)) re = modCoin.PayCoin(optId, 1, useCoinValue, classMethod, param) if re > 0: re = modCoin.GainCoin(optId, coinType, coinValue, classMethod, param) if re: return Gcore.out(optId, {'Result': re}) else: return Gcore.error(optId, -20002997) #非法操作 else: return Gcore.error(optId, -20002995) #支付失败
def SpeedRapidPractise(self, param={}): '''加速突飞训练的冷却时间''' optId = 15094 IsSpeed = param.get('IsSpeed') TimeStamp = param['ClientTime'] TodayDate = time.strftime('%Y-%m-%d', time.localtime(TimeStamp)) modGround = Gcore.getMod('Building_ground', self.uid) RapidRecord = modGround.getRapidRecord(TodayDate) if not RapidRecord: RapidCount = 0 IsOverFlow = 0 CDValue = 0 else: RapidCount = RapidRecord['PractiseCount'] IsOverFlow = RapidRecord['IsOverFlow'] TotalCD = RapidRecord['CDValue'] SecondsPast = TimeStamp - RapidRecord['LastRapidTime'] CDValue = max(TotalCD - SecondsPast, 0) if CDValue <= 0: IsOverFlow = 0 if not IsSpeed: #不是加速 body = {} body['TimeStamp'] = TimeStamp body['IsOverFlow'] = IsOverFlow body['CDValue'] = CDValue body['RapidCout'] = RapidCount return Gcore.out(optId, body=body) #加速冷却时间 if CDValue <= 0: return Gcore.error(optId, -15094001) #冷却时间为0 CoinType = 1 CoinValue = calSpeedCost(4, CDValue) #扣钱 modCoin = Gcore.getMod('Coin', self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) pay = modCoin.PayCoin(optId, CoinType, CoinValue, classMethod, param) if pay < 0: return Gcore.error(optId, -15094002) #扣钱失败 #更新突飞记录表 modGround.speedCD() body = {} body['GoldenCost'] = pay body['CDValue'] = 0 body['SpeedTime'] = CDValue body['IsOverFlow'] = 0 body['TimeStamp'] = TimeStamp return Gcore.out(optId, body=body)
def receiveAttachment(self, mailId, optId, classMethod, param): ''' 获取附件 @param mailId: 邮件ID @param optId: @param classMethod: @param param: @return 返回成功接收的附件 GoodsType1装备,2道具,3资源 GoodsId 装备类型ID,道具类型ID,资源类型ID GoodsNum 物品数量 EquipId 装备ID,其他类型该值为0 ''' mailConId = self.db.out_field( 'tb_mail', 'MailConId', 'MailId=%s AND ToUserId=%s' % (mailId, self.uid)) locktime = int(time.time()) row = {'AttachmentLock': locktime} where = 'MailConId=%s and AttachmentLock<%s' % (mailConId, locktime - 5 ) #5秒内只能有一次操作,防止并发 affectedrows = self.db.update('tb_mail_con', row, where) if affectedrows: attachDicts = self.db.out_field('tb_mail_con', 'Attachment', 'MailConId=%s' % mailConId) attachDicts = json.loads(attachDicts) if attachDicts else [] #判断背包是否有足够的格子 modBag = Gcore.getMod('Bag', self.uid) modCoin = Gcore.getMod('Coin', self.uid) if not modBag.canAddInBag(attachDicts): return [] for attachDict in attachDicts: if attachDict['GoodsType'] in (1, 2, 4, 5): result = modBag.addGoods(attachDict['GoodsType'], attachDict['GoodsId'], attachDict['GoodsNum'], False) attachDict['EquipId'] = result[0] elif attachDict['GoodsType'] == 3: if attachDict['GoodsId'] == 5: #加荣誉 pMod = Gcore.getMod('Player', self.uid) pMod.gainHonour(attachDict['GoodsNum'], optId) elif attachDict['GoodsId'] == 6: #加贡献 clubMod = Gcore.getMod('Building_club', self.uid) clubBuildInfo = clubMod.getClubBuildingInfo() clubId = clubMod.getUserClubId() if clubBuildInfo and clubId: clubMod.gainDeveote( clubId, 3, devoteNum=attachDict['GoodsNum']) else: modCoin.GainCoin(optId, attachDict['GoodsId'], attachDict['GoodsNum'], classMethod, param) attachDict['EquipId'] = 0 #更新附件 self.db.update('tb_mail_con', {'Attachment': ''}, 'MailConId=%s' % mailConId) return attachDicts return 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) #支付失败
def CreateWallDefense(self,p={}): '''建造防御工事 Lizr''' optId = 92001 defenseType = int(p['DefenseType']) x = p['x'] y = p['y'] xSize = p['xSize'] ySize = p['ySize'] buildingInfo = self.mod.getWallInfo() if buildingInfo is None: return Gcore.error(optId,-92001998)#非法操作 wallLevel = buildingInfo.get('BuildingRealLevel') if defenseType/100 != 2: #200~299 return Gcore.error(optId,-92001998) #非法操作 Size = Gcore.getCfg('tb_cfg_soldier',defenseType,'Size') if str(xSize)+'*'+str(ySize)!=Size and str(ySize)+'*'+str(xSize)!=Size: #非配置的尺寸 1*3 return Gcore.error(optId,-92001001) #尺寸不合法 # if not self.mod.checkWallCoord(x,y): #@todo: 加上布防坐标验证 # return Gcore.error(optId,-92001002) #坐标不合法 maxCount = Gcore.getCfg('tb_cfg_wall',wallLevel,'DefenseType%s'%defenseType) defenseNum = self.mod.getDefenseNum() if defenseNum.get(defenseType,0)>=maxCount: return Gcore.error(optId,-92001003) #超出最大可建数量 bookMod = Gcore.getMod('Book',self.uid) coinMod = Gcore.getMod('Coin',self.uid) defenseLevel = bookMod.getTechsLevel(1).get(defenseType,0)#从书院获取 if defenseLevel==0: defenseLevel=1 defenseCfg = Gcore.getCfg('tb_cfg_soldier_up',(defenseType,defenseLevel)) cost = defenseCfg.get('MakeCost') costType = defenseCfg.get('MakeCostType') payState = coinMod.PayCoin(optId,costType,cost,'WallUI.CreateWallDefense',p) # payState = 1 if payState: data={ 'UserId':self.uid, 'SoldierType':defenseType, 'SoldierLevel':defenseLevel, 'xSize':xSize,'ySize':ySize, 'x':x,'y':y, 'MakeCost':cost, } DefenseId = self.mod.createDefense(data) recordData = {'uid':self.uid,'ValType':0,'Val':1,'Level':defenseLevel} return Gcore.out(optId,{'WallDefenseId':DefenseId},mission=recordData) else: Gcore.error(optId,-92001995) #支付失败
def HandleApply(self, param={}): """处理好友申请""" optId = 19003 timeStamp = param["ClientTime"] friendUserIds = param["FriendUserIds"] handleType = param["HandleType"] recordData = {} # 任务记录 if not friendUserIds: return Gcore.error(optId, -19003999) # 参数错误 if handleType == 0: """拒绝添加""" # self.mod.updateFriendShip(friendUserIds, self.uid, 0, timeStamp) self.mod.refuseApply(friendUserIds, self.uid, timeStamp) mailMod = Gcore.getMod("Mail", self.uid) nickName = self.mod.getUserInfo("NickName") # mailMod.sendMail(friendUserIds, '拒绝好友申请', nickName+'拒绝了你的好友申请', 1)#拒绝好友,调用邮件发送信息给对方 for toUserId in friendUserIds: mailMod.sendSystemMail(toUserId, [], optId, other=[nickName]) elif handleType == 1: """确认添加""" # 判断玩家自己的好友数是否已达上限 uLimitNum = Gcore.getCfg("tb_cfg_friend_limit", self.mod.getUserLevel(), "FriendNumLimit") uNowNum = self.mod.countFriend(2) if uNowNum >= uLimitNum: return Gcore.error(optId, -19003001) # 好友超过上限 # 如果对方好友已达上限,则拒绝本次添加请求 validId = [] for fid in friendUserIds: tmpMod = Gcore.getMod("Friend", fid) limitNum = Gcore.getCfg("tb_cfg_friend_limit", tmpMod.getUserLevel(), "FriendNumLimit") nowNum = tmpMod.countFriend(2) if nowNum >= limitNum: # self.mod.updateFriendShip(fid, self.uid, 0, timeStamp) self.mod.refuseApply(fid, self.uid, timeStamp) else: validId.append(fid) if len(validId) == 0: return Gcore.error(optId, -19003002) # 如果玩家添加的好友数多于所能添加的个数,则失败 if uNowNum + len(validId) > uLimitNum: return Gcore.error(optId, -19003001) for friendUserId in validId: self.mod.insFriendShip(self.uid, friendUserId, 2) self.mod.updateFriendShip(friendUserId, self.uid, 2, timeStamp) recordData = {"uid": self.uid, "ValType": 0, "Val": 1} Gcore.getMod("Mission", friendUserId).missionTrigger(optId) # 触发被同意好友更新 else: return Gcore.error(optId, -19003999) # 参数错误 return Gcore.out(optId, {}, mission=recordData)
def CreateRole(self,p={}): '''注册用户 by zhanggh''' AccountId = p.get('TotalServiceId') nickName = p.get('NickName') camp = p.get('UserCamp') userIcon = p.get('UserIcon') OldAccount = p.get('OldAccount') #是否老用户 if (not AccountId) or (not nickName) or (not camp) or (not userIcon): return -10002999 #参数错误 PlayerCfg = Gcore.loadCfg(Gcore.defined.CFG_PLAYER) nickNameMin = PlayerCfg.get('NickNameMin') nickNameMax = PlayerCfg.get('NickNameMax') flag=filterInput(nickName,nickNameMin,nickNameMax) if flag==-1: return -10002993#字数字数限制 elif flag==-2: return -10002991#特殊字符 elif flag==-3: return -10002992#敏感字 if camp not in [1,2,3]: return -10002004#阵营不正确 if userIcon not in [1,2,3,4,5]: return -10002005#头像不正确 print 'CheckNickName',flag #获取用户ID,暂时没有角色UserId才能注册 UserId = self.getUserIdByAccount(AccountId) if not UserId:#没有用户注册一个,建立AccountId与Uid关系,创建用户 #验证用户昵称 hasSameName = self.db.out_field('tb_user','Count(1)',"NickName='%s'"%nickName) if hasSameName: return -10002001#用户昵称已存在 UserId = self.CreateUser(p) if not UserId: return -10002002#注册失败 try: mod_play = Gcore.getMod('Player', uid=UserId) userData = mod_play.PlayerInfo() try: Gcore.getMod('Request', UserId).CreatedPlayer(AccountId) except Exception,e: print '通知总服已创建号失败',e except Exception, e: userData = {} print '登陆失败,', e return -10002003
def CancelBuilding(self, param={}): '''通用:取消建筑建造或升级''' optId = 15003 BuildingId = param["BuildingId"] TimeStamp = param['ClientTime'] BuildingInfo = self.mod.getBuildingById(BuildingId, ['BuildingPrice', 'BuildingType', 'CoinType', 'LastOptType'], TimeStamp=TimeStamp) if not BuildingInfo: return Gcore.error(optId, -15003003) #用户没有该建筑 #BuildingType < 100 是建筑;大于100是装饰; if BuildingInfo['BuildingType'] < 100 and \ BuildingInfo['BuildingState'] == 0: return Gcore.error(optId, -15003004) #建筑已建造或升级完成,不能取消。 BuildingType = BuildingInfo['BuildingType'] CostValue = BuildingInfo["BuildingPrice"] CostType = BuildingInfo["CoinType"] #返钱 CancelReturn = Gcore.loadCfg( Gcore.defined.CFG_BUILDING)["CancelReturn"] #返还比例 modCoin = Gcore.getMod('Coin', self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) gain = modCoin.GainCoin(optId, CostType, int(CostValue * CancelReturn), classMethod, param) if gain < 0: return Gcore.error(optId, -15003005) #增加货币失败 #建筑正在建造 :如果是装饰,删掉。 if BuildingInfo['BuildingType'] > 100 or \ BuildingInfo['BuildingState'] == 1: self.mod.deleteBuildingById(BuildingId) else: #更新建筑表 UpInfo = {} UpInfo['CompleteTime'] = TimeStamp UpInfo['BuildingLevel'] = BuildingInfo['BuildingRealLevel'] UpInfo['LastOptType'] = 2 self.mod.updateBuildingById(UpInfo, BuildingId) #不同类型的建筑进行不同的操作 # + todo if BuildingType in (6, 8): #校场 兵营 工坊:计算士兵 modCamp = Gcore.getMod('Building_camp', self.uid) modCamp.updateStorage(BuildingId, last_changed_time=TimeStamp, last_cal_time=TimeStamp) return Gcore.out(optId, {'Coin%s'%CostType:modCoin.getCoinNum(CostType), "RetValue":int(CostValue * CancelReturn)})
def CreateRole(self, p={}): '''注册用户 by zhanggh''' AccountId = p.get('TotalServiceId') nickName = p.get('NickName') camp = p.get('UserCamp') userIcon = p.get('UserIcon') OldAccount = p.get('OldAccount') #是否老用户 if (not AccountId) or (not nickName) or (not camp) or (not userIcon): return -10002999 #参数错误 PlayerCfg = Gcore.loadCfg(Gcore.defined.CFG_PLAYER) nickNameMin = PlayerCfg.get('NickNameMin') nickNameMax = PlayerCfg.get('NickNameMax') flag = filterInput(nickName, nickNameMin, nickNameMax) if flag == -1: return -10002993 #字数字数限制 elif flag == -2: return -10002991 #特殊字符 elif flag == -3: return -10002992 #敏感字 if camp not in [1, 2, 3]: return -10002004 #阵营不正确 if userIcon not in [1, 2, 3, 4, 5]: return -10002005 #头像不正确 print 'CheckNickName', flag #获取用户ID,暂时没有角色UserId才能注册 UserId = self.getUserIdByAccount(AccountId) if not UserId: #没有用户注册一个,建立AccountId与Uid关系,创建用户 #验证用户昵称 hasSameName = self.db.out_field('tb_user', 'Count(1)', "NickName='%s'" % nickName) if hasSameName: return -10002001 #用户昵称已存在 UserId = self.CreateUser(p) if not UserId: return -10002002 #注册失败 try: mod_play = Gcore.getMod('Player', uid=UserId) userData = mod_play.PlayerInfo() try: Gcore.getMod('Request', UserId).CreatedPlayer(AccountId) except Exception, e: print '通知总服已创建号失败', e except Exception, e: userData = {} print '登陆失败,', e return -10002003
def getRelatedUsers(self): ''' 获取联系用户 ''' modFriend = Gcore.getMod('Friend', self.uid) friends = modFriend.getFriends() #好友 modClub = Gcore.getMod('Building_club', self.uid) clubMembers = modClub.getClubMembers() return friends, clubMembers
def FullAddSoldier(self, param={}): '''填满兵营或工坊的剩余训练空间''' optId = 15031 BuildingId = param['BuildingId'] TimeStamp = param['ClientTime'] modBuilding = Gcore.getMod('Building', self.uid) BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp) if not BuildingInfo: return Gcore.error(optId, -15031001) #玩家没有该建筑 if BuildingInfo['BuildingState'] == 1: return Gcore.error(optId, -15031002) #建筑正在建造 if BuildingInfo['BuildingType'] not in (6, 8): return Gcore.error(optId, -15031003) #建筑不是兵营或工坊 modCamp = Gcore.getMod('Building_camp', self.uid) spawn_detail = modCamp.getSoldierStorage(BuildingInfo, TimeStamp) MaxNum = Gcore.getCfg( 'tb_cfg_building_up', (BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel']), 'MakeValue') buy_cnt = MaxNum - spawn_detail['StorageNum'] print '兵营或工坊的最大数量', MaxNum print '当前时刻的数量', spawn_detail['StorageNum'] print '购买数量', buy_cnt if buy_cnt < 0: return Gcore.error(optId, -15031004) #兵营或工坊已满 elif buy_cnt > 0: coin_need = calSpeedCost(3, buy_cnt) class_method = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) modCoin = Gcore.getMod('Coin', self.uid) pay = modCoin.PayCoin(optId, 1, coin_need, class_method, param) if pay < 0: return Gcore.error(optId, -15031005) #支付失败 #将兵营置满 modCamp.fullAddSoldier( BuildingId, BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel'], max(spawn_detail['LastChangedTime'], TimeStamp), TimeStamp) else: pay = 0 body = {} body['StorageNum'] = MaxNum body['BuyCnt'] = buy_cnt body['GoldenCoinCost'] = pay body['TimeStamp'] = TimeStamp return Gcore.out(optId, body=body)
def GetReward(self,p={}): ''' 领取任务奖励 ''' optId=22003 mId=p['MID'] mCfg = Gcore.getCfg('tb_cfg_mission',mId) if mCfg is None: return Gcore.error(optId,-22003001)#任务不存在 # mInfo = self.mod.getMissionInfo(mId) # if mInfo is None: # return Gcore.error(optId,-22003001)#任务不存在 # #1: 新接,2:进行中,3:已完成,4:已领取奖励 # elif mInfo.get('Status')!=3: # return Gcore.error(optId,-22003002)#任务未完成 whereClause = 'UserId=%s AND MissionId=%s AND Status=3'%(self.uid,mId) updateFlag = self.mod.updateMissionByWhere({'Status':4},whereClause)#先更新任务状态,防止并发 if not updateFlag: return Gcore.error(optId,-22003002)#任务未完成 #领取奖励 coinMod = Gcore.getMod('Coin',self.uid) playerMod = Gcore.getMod('Player',self.uid) rewardMod = Gcore.getMod('Reward',self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) expReward = mCfg.get('RewardExp',0) JCReward = mCfg.get('RewardJCoin',0) GCReward = mCfg.get('RewardGCoin',0) GReward = mCfg.get('RewardGold',0) #发放奖励 playerMod.addUserExp(0,expReward,optId) coinMod.GainCoin(optId,1,GReward,classMethod,p) coinMod.GainCoin(optId,2,JCReward,classMethod,p) coinMod.GainCoin(optId,3,GCReward,classMethod,p) rt1 = mCfg.get('RewardType1',0) rt2 = mCfg.get('RewardType2',0) equipIds = [] if rt1!=0: f = rewardMod.reward(optId,p,rt1,mCfg['GoodsId1'],mCfg['GoodsNum1']) if rt1==1 and isinstance(f,list): equipIds = equipIds+f if rt2!=0: f = rewardMod.reward(optId,p,rt2,mCfg['GoodsId2'],mCfg['GoodsNum2']) if rt2==1 and isinstance(f,list): equipIds = equipIds+f # self.mod.updateMissions({mId:{'Status':4}}) self.mod.getNewMission(mId) myMissions =self.mod.getMyMissions() myMissions = com.list2dict(myMissions,0) re={'EIds':equipIds,'MLS':myMissions} return Gcore.out(optId,re)
def collectCoin(self,optId,BuildingType,BuildingId,CollectTimeStamp=None,StorageReq=None,param=''): ''' :收集资源 @param optId:协议号 @param BuildingType:建筑类型 @param BuildingId:建筑ID @param CollectTimeStamp:计算时间 @param StorageReq:请求收集资源(大于后台时候以后台计算为准) @return: {}: 成功收集 0:没有可收集资源 -1:建筑修复中 ''' coinMod = Gcore.getMod('Coin',self.uid) CoinType = 2 if BuildingType == 2 else 3 MyCoin = coinMod.getCoinNum(CoinType)#获取我的储量 CoinVol = self.buildingMod.cacStorageSpace(CoinType)#查询资源容量 MyCoin = CoinVol if MyCoin>CoinVol else MyCoin#当已有资源大于容量时候,将拥有数目设置为最大 CollectTimeStamp = time.time() if CollectTimeStamp is None else CollectTimeStamp StorageInfo = self.touchBuildingStorage(BuildingId,CollectTimeStamp) StorageCal = StorageInfo.get('Storage') if StorageCal==0:#没可收集资源 return {'Remain':StorageCal,'Diff':0,'CNum':0,'NowCoin':MyCoin} elif StorageCal<=0:#修复中 return -1 #计算收集数量,剩余数量 if not StorageReq: diff = 0 else: diff = StorageCal-StorageReq StorageCal = StorageReq if 0<StorageReq<=StorageCal else StorageCal#消除误差,前台计算总比后台少 #藩国损失 hasHolder = Gcore.getMod('Building_hold',self.uid).hasHolder() collectRatio = (1-Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD).get('GiveRatio',0.05)) if hasHolder else 1 storageReduce = StorageCal*collectRatio if (MyCoin+storageReduce)>CoinVol: CollectNum = CoinVol-MyCoin Remain = StorageCal-math.ceil(CollectNum/collectRatio) else: Remain = 0 CollectNum = storageReduce # Remain = MyCoin+StorageCal-CoinVol # Remain = 0 if Remain <0 else Remain # CollectNum = StorageCal-Remain#收集数量 #增加资源数量并更新剩余 flag = coinMod.GainCoin(optId,CoinType,CollectNum,'Building_resoureUI.CollectCoin',param) if flag: self.updateStorage(Remain,BuildingId,CollectTimeStamp) return {'Remain':Remain,'Diff':diff,'CNum':CollectNum,'NowCoin':MyCoin+CollectNum,'Storage':Remain}
def InviteGenerals(self, param={}): '''招贤馆:招募武将''' optId = 15007 GeneralType = param["GeneralType"] InviteTimeStamp = param['ClientTime'] InviteInfo = self.mod.getInvite() if not InviteInfo or InviteTimeStamp > InviteInfo['EndTime']: return Gcore.error(optId, -15007004) Invites = [ InviteInfo["GeneralId1"], InviteInfo["GeneralId2"], InviteInfo["GeneralId3"] ] if GeneralType not in Invites: return Gcore.error(optId, -15007001) #此武将不可招募 modGeneral = Gcore.getMod('General', self.uid) if GeneralType in modGeneral.getGeneralTypeList(): return Gcore.error(optId, -15007002) #已有该类型武将 FreeGeneralHomes = self.mod.getFreeGeneralHomes(InviteTimeStamp) if not FreeGeneralHomes: return Gcore.error(optId, -15007003) #没有剩余的点将台 GeneralInfo = Gcore.getCfg('tb_cfg_general', key=GeneralType) InviteCostType = GeneralInfo["InviteCostType"] InviteCost = GeneralInfo["InviteCost"] #开始支付流程 print 'InviteCostType', InviteCostType print 'InviteCost', InviteCost modCoin = Gcore.getMod('Coin', self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) pay = modCoin.PayCoin(optId, InviteCostType, InviteCost, classMethod, param) if pay < 0: return Gcore.error(optId, -15007995) #支付失败 GeneralId = modGeneral.addNewGeneral(GeneralType, min(FreeGeneralHomes), InviteTimeStamp) recordData = {'uid': self.uid, 'ValType': GeneralType, 'Val': 1} #成就记录 return Gcore.out(optId, body={ "Location": min(FreeGeneralHomes), "GeneralId": GeneralId, "GeneralType": GeneralType }, achieve=recordData, mission=recordData)
def ChangeSoldierNum(self, param={}): '''校场:改变武将的带兵类型,数量''' optId = 15103 GeneralId = param['GeneralId'] SoldierNum = param['SoldierNum'] SoldierType = param['SoldierType'] TimeStamp = param['ClientTime'] modGeneral = Gcore.getMod('General', self.uid) Generals = modGeneral.getLatestGeneralInfo(TimeStamp=TimeStamp) GeneralsOnEmbattle = [ General for General in Generals if General["PosId"] != 0 ] GeneralInfo = None SoldierOnEmbattle = 0 for GeneralOnEmbattle in GeneralsOnEmbattle: if GeneralOnEmbattle['GeneralId'] == GeneralId: GeneralInfo = GeneralOnEmbattle if GeneralOnEmbattle['TakeType'] == SoldierType: SoldierOnEmbattle += GeneralOnEmbattle['TakeNum'] kLeader = Gcore.loadCfg( Gcore.defined.CFG_BATTLE)["kLeaderAddNum"] #每统帅带兵数 if not GeneralInfo: return Gcore.error(optId, -15103001) #该武将没上阵或没有该武将 if SoldierNum > (GeneralInfo['LeaderValue'] * kLeader): #需要改成读配置 return Gcore.error(optId, -15103002) #带兵数量过大 #校场的士兵数量 modCamp = Gcore.getMod('Building_camp', self.uid) Soldiers = modCamp.getSoldierNum(TimeStamp) #空闲士兵数量 SoldierFree = Soldiers.get('Soldier%s' % SoldierType, 0) - SoldierOnEmbattle #武将带兵数量 if SoldierNum <= GeneralInfo['TakeNum']: TakeNum = SoldierNum else: TakeNum = min(SoldierNum, GeneralInfo['TakeNum'] + SoldierFree) UpGeneralInfo = {"TakeNum": TakeNum, "TakeType": SoldierType} modGeneral.updateGeneralById(UpGeneralInfo, GeneralId) recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1} #成就、任务记录 return Gcore.out(optId, body={ "TakeNum": TakeNum, "TakeType": SoldierType }, mission=recordData)
def defenseDamage(self,para): '''协议号5: 防御工事损坏''' UserId = para['UserId'] Defense = para['Defense'] #有损坏变化的工事 b = Base(UserId) tb_wall_defense = b.tb_wall_defense() for k,v in Defense.iteritems(): sql = "UPDATE %s SET LifeRatio='%s' WHERE WallDefenseId='%s'"%(tb_wall_defense,v,k) result = self.db.execute(sql) print 'result:sql',result,sql Gcore.getMod('Redis',UserId).offCacheWallDefense() #更新缓存
def BuyResource(self, param={}): '''商城购买资源''' optId=20002 classMethod = '%s,%s'%(self.__class__.__name__,sys._getframe().f_code.co_name) resSaleId = param['ResSaleId'] resSaleCfg = Gcore.getCfg('tb_cfg_shop_res_sale', resSaleId) coinType = resSaleCfg['CoinType'] percent = resSaleCfg['AddPercent'] buildingMod = Gcore.getMod('Building', self.uid) maxCoin = buildingMod.cacStorageSpace(coinType) modCoin = Gcore.getMod('Coin', self.uid) currCoinNum = modCoin.getCoinNum(coinType) if percent < 1: coinValue = maxCoin*percent#增加货币 elif percent == 1: coinValue = maxCoin - currCoinNum#增加货币 percent = coinValue / maxCoin #print 'percent', percent resSaleList = Gcore.getCfg('tb_cfg_shop_res_sale') resSaleList = filter(lambda dic:dic['AddPercent'] <= percent and dic['CoinType'] == coinType, resSaleList.values()) resSaleCfg = max(resSaleList, key=lambda sale:sale['AddPercent']) # print resSaleList # resSaleList.sort(key=lambda sale:sale['AddPercent']) # if resSaleList: # resSaleCfg=resSaleList.pop() else: return Gcore.error(optId, -20002001)#percent错误,大于1 if currCoinNum + coinValue > maxCoin: return Gcore.error(optId, -20002002)#超过资源上限 kPrice1 = resSaleCfg['kPrice1'] kPrice2 = resSaleCfg['kPrice2'] #支付黄金 useCoinValue = int(math.ceil(coinValue*kPrice1*maxCoin**kPrice2)) re = modCoin.PayCoin(optId, 1, useCoinValue, classMethod, param) if re > 0: re = modCoin.GainCoin(optId, coinType, coinValue, classMethod, param) if re: return Gcore.out(optId, {'Result':re}) else: return Gcore.error(optId, -20002997)#非法操作 else: return Gcore.error(optId, -20002995)#支付失败
def FullAddSoldier(self, param={}): '''填满兵营或工坊的剩余训练空间''' optId = 15031 BuildingId = param['BuildingId'] TimeStamp = param['ClientTime'] modBuilding = Gcore.getMod('Building', self.uid) BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=TimeStamp) if not BuildingInfo: return Gcore.error(optId, -15031001) #玩家没有该建筑 if BuildingInfo['BuildingState'] == 1: return Gcore.error(optId, -15031002) #建筑正在建造 if BuildingInfo['BuildingType'] not in (6, 8): return Gcore.error(optId, -15031003) #建筑不是兵营或工坊 modCamp = Gcore.getMod('Building_camp', self.uid) spawn_detail= modCamp.getSoldierStorage(BuildingInfo, TimeStamp) MaxNum = Gcore.getCfg('tb_cfg_building_up', (BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel']), 'MakeValue') buy_cnt = MaxNum - spawn_detail['StorageNum'] print '兵营或工坊的最大数量', MaxNum print '当前时刻的数量', spawn_detail['StorageNum'] print '购买数量', buy_cnt if buy_cnt < 0: return Gcore.error(optId, -15031004) #兵营或工坊已满 elif buy_cnt > 0: coin_need = calSpeedCost(3, buy_cnt) class_method = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) modCoin = Gcore.getMod('Coin', self.uid) pay = modCoin.PayCoin(optId, 1, coin_need, class_method, param) if pay < 0: return Gcore.error(optId, -15031005) #支付失败 #将兵营置满 modCamp.fullAddSoldier(BuildingId, BuildingInfo['BuildingType'], BuildingInfo['BuildingRealLevel'], max(spawn_detail['LastChangedTime'], TimeStamp), TimeStamp) else: pay = 0 body = {} body['StorageNum'] = MaxNum body['BuyCnt'] = buy_cnt body['GoldenCoinCost'] = pay body['TimeStamp'] = TimeStamp return Gcore.out(optId, body=body)
def EventTrigger(self,p={}): '''事件触发 1.建筑完成, 2.建筑升级完成, 3.科技升级完成''' optId = 22004 eId = p['EID'] if eId not in [1,2,3]: return Gcore.error(optId,-22004001)#事件ID未定义 self.mod.missionTrigger(eId) Gcore.getMod('Building_home',self.uid).achieveTrigger(eId) return Gcore.out(optId,{})
def getMaxSoldierNum(self, buildings=None, time_stamp=None): '''计算校场士兵的最大数量''' if not isinstance(buildings, (list, tuple)): modBuilding = Gcore.getMod('Building', self.uid) buildings = modBuilding.getBuildingByType(7, TimeStamp=time_stamp) #校场 MaxNum = 0 for building in buildings: if building['BuildingState'] == 1 : continue MaxNum += Gcore.getCfg('tb_cfg_building_up', (7, building["BuildingRealLevel"]), "SaveValue") modInter = Gcore.getMod('Inter', self.uid) return modInter.getInterEffect(3, MaxNum) #内政加成
def EventTrigger(self, p={}): '''事件触发 1.建筑完成, 2.建筑升级完成, 3.科技升级完成''' optId = 22004 eId = p['EID'] if eId not in [1, 2, 3]: return Gcore.error(optId, -22004001) #事件ID未定义 self.mod.missionTrigger(eId) Gcore.getMod('Building_home', self.uid).achieveTrigger(eId) return Gcore.out(optId, {})
def UpgradeWallTech(self,p={}): '''城墙升级科技''' optId = 15054 techType = p.get('TechType') buildingId = p.get('BuildingId') now = time.time() techCategory = 1 #判断传入参数是否合法 techCfg = Gcore.getCfg('tb_cfg_wall_school') ts = [k[0] for k in techCfg.keys()] if techType<200 or techType not in ts: return Gcore.error(optId,-15054999) #获院建筑信息 building = Gcore.getMod('Building',self.uid).getBuildingById(buildingId) if not building or building.get('BuildingType')!=19: return Gcore.error(optId,-15054901)#建筑不存在 bookLevel = building.get('BuildingRealLevel') flag = self.mod.getUpgradingTech(buildingId) if flag: return Gcore.error(optId,-15054001)#学习占用中 tech = self.mod.getTech(techCategory,techType) techLevel = tech.get('TechLevel') techMaxLevel = self.mod.getTechMaxLevel(techCategory,techType,bookLevel) if techMaxLevel is None or techLevel >= techMaxLevel: return Gcore.error(optId,-15054002)#城墙等级不足 techCfg = techCfg.get((techType,techLevel+1))#获取科技类型与等级配置 needTime = techCfg.get('LearnTime') itemId = techCfg.get('ItemIdNeed') itemNum = techCfg.get('ItemNeedNeed') flag = Gcore.getMod('Bag',self.uid).useItems(itemId,itemNum) if flag:#支付成功 data = {'TechLevel':techLevel+1, 'LastStartTime':now, 'LastEndTime':now+needTime, 'BuildingId':buildingId} self.mod.updateTech(techCategory,techType,data) else: return Gcore.error(optId,-15054003)#道具数量不足 tech = self.mod.getUpgradingTech(buildingId) return Gcore.out(optId,{'Tech':tech})
def getMaxSoldierNum(self, buildings=None, time_stamp=None): '''计算校场士兵的最大数量''' if not isinstance(buildings, (list, tuple)): modBuilding = Gcore.getMod('Building', self.uid) buildings = modBuilding.getBuildingByType( 7, TimeStamp=time_stamp) #校场 MaxNum = 0 for building in buildings: if building['BuildingState'] == 1: continue MaxNum += Gcore.getCfg('tb_cfg_building_up', (7, building["BuildingRealLevel"]), "SaveValue") modInter = Gcore.getMod('Inter', self.uid) return modInter.getInterEffect(3, MaxNum) #内政加成
def lost_connection(self, server, channel): ckey = channel.peername #自改abu为channel加上此属性,因socket已不可用,不能getpeername msg = 'lost a connection:%s' % str(ckey) comm.trace(msg) if ckey in self.Clients: try: #清空些用户的资料 uid = self.Clients[ckey]['uid'] if uid: Gcore.getMod('Login', uid).logout() #更新 Gcore.onlineUser.pop(uid,None) #用户落线 Gcore.delUserStorage(uid) except Exception,e: print 'lost_connection >> ',e self.Clients.pop(ckey)
def DefenseInfo(self, p={}): '''布防信息界面 Lizr''' optId = 92004 buildingInfo = self.mod.getWallInfo() if not buildingInfo: return Gcore.error(optId, -92004998) wallLevel = buildingInfo.get('BuildingRealLevel') bookMod = Gcore.getMod('Book', self.uid) TechsDic = bookMod.getTechsLevel(1) DefenseCount = self.mod.getDefenseCount() #分类统计防御工事数量 DefenseLevels = {} for k, v in TechsDic.iteritems(): if k > 200 and k < 300: if v == 0: v = 1 DefenseLevels[k] = v if k not in DefenseCount: #没有负为0 DefenseCount[k] = 0 DefenseInfo = self.mod.getAllDefenseInfo() import copy TrapInfo = {} for k, v in copy.deepcopy(DefenseInfo).iteritems(): if v.get('SoldierType') > 300: TrapInfo[k] = DefenseInfo.pop(k) GeneralInfo = self.mod.getDefenseGeneral() body = { 'WallLevel': wallLevel, 'DefenseLevels': DefenseLevels, 'DefenseInfo': DefenseInfo, 'TrapInfo': TrapInfo, 'GeneralInfo': GeneralInfo, 'DefenseCount': DefenseCount, 'OpenSoldier': Gcore.common.list2dict( Gcore.getMod('Building_camp', self.uid).openSoliders()) #最高等级兵营开放的兵种,按开放等级排序 } recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1} return Gcore.out(optId, body, mission=recordData)
def SpeedupInvite(self, param={}): '''招贤馆:黄金加速刷新''' optId = 15008 BuildingId = param['BuildingId'] SpeedUpTimeStamp = param['ClientTime'] modBuilding = Gcore.getMod('Building', self.uid) BuildingInfo = modBuilding.getBuildingById(BuildingId, TimeStamp=SpeedUpTimeStamp) if not BuildingInfo: return Gcore.error(optId, -15008901) #用户没有该建筑 if BuildingInfo['BuildingState'] == 1: return Gcore.error(optId, -15008902) #建筑正在建造 if BuildingInfo['BuildingType'] != 13: return Gcore.error(optId, -15008903) #该建筑不是招贤馆 InviteInfo = self.mod.getInvite() if not InviteInfo or InviteInfo['EndTime'] < SpeedUpTimeStamp: return Gcore.error(optId, -15008001) #没有招募记录 #获取加速次数 SpeedCount = self.mod.cacSpeedCount(InviteInfo['SpeedCount'], InviteInfo['LastSpeedDate'], SpeedUpTimeStamp) SpeedCount += 1 coinValue = 5 #读配置 #开始支付流程 modCoin = Gcore.getMod('Coin', self.uid) classMethod = '%s.%s' % (self.__class__.__name__, sys._getframe().f_code.co_name) pay = modCoin.PayCoin(optId, 1, coinValue, classMethod, param) if pay < 0: return Gcore.error(optId, -15008995) #支付失败 BuildingLevel = BuildingInfo['BuildingRealLevel'] ChosenGenerals = self.mod.chooseGenerals() self.mod.updateInvite(ChosenGenerals, BuildingLevel, SpeedUpTimeStamp, SpeedCount) RemainedTime = Gcore.getCfg('tb_cfg_building_up', (13, BuildingLevel), 'RefreshValue') RetDic = {} RetDic["CostValue"] = coinValue RetDic["NextCostValue"] = coinValue RetDic["RemainedTime"] = RemainedTime RetDic["Generals"] = ChosenGenerals return Gcore.out(optId, RetDic)
def lost_connection(self, server, channel): ckey = channel.peername #自改abu为channel加上此属性,因socket已不可用,不能getpeername msg = 'lost a connection:%s' % str(ckey) comm.trace(msg) if ckey in self.Clients: try: #清空些用户的资料 uid = self.Clients[ckey]['uid'] if uid > 0: Gcore.getMod('Login', uid).logout() #更新 Gcore.onlineUser.pop(uid, None) #用户落线 Gcore.delUserStorage(uid) except Exception, e: print 'lost_connection >> ', e self.Clients.pop(ckey, None)
def receiveAttachment(self, mailId, optId, classMethod, param): ''' 获取附件 @param mailId: 邮件ID @param optId: @param classMethod: @param param: @return 返回成功接收的附件 GoodsType1装备,2道具,3资源 GoodsId 装备类型ID,道具类型ID,资源类型ID GoodsNum 物品数量 EquipId 装备ID,其他类型该值为0 ''' mailConId = self.db.out_field('tb_mail', 'MailConId', 'MailId=%s AND ToUserId=%s'%(mailId, self.uid)) locktime = int(time.time()) row = {'AttachmentLock': locktime} where = 'MailConId=%s and AttachmentLock<%s'%(mailConId, locktime - 5) #5秒内只能有一次操作,防止并发 affectedrows = self.db.update('tb_mail_con', row, where) if affectedrows: attachDicts = self.db.out_field('tb_mail_con', 'Attachment', 'MailConId=%s'%mailConId) attachDicts = json.loads(attachDicts) if attachDicts else [] #判断背包是否有足够的格子 modBag = Gcore.getMod('Bag', self.uid) modCoin = Gcore.getMod('Coin', self.uid) if not modBag.canAddInBag(attachDicts): return [] for attachDict in attachDicts: if attachDict['GoodsType'] in (1, 2, 4, 5): result = modBag.addGoods(attachDict['GoodsType'], attachDict['GoodsId'], attachDict['GoodsNum'], False) attachDict['EquipId'] = result[0] elif attachDict['GoodsType'] == 3: if attachDict['GoodsId'] == 5: #加荣誉 pMod = Gcore.getMod('Player', self.uid) pMod.gainHonour(attachDict['GoodsNum'], optId) elif attachDict['GoodsId'] == 6: #加贡献 clubMod = Gcore.getMod('Building_club', self.uid) clubBuildInfo = clubMod.getClubBuildingInfo() clubId = clubMod.getUserClubId() if clubBuildInfo and clubId: clubMod.gainDeveote(clubId, 3, devoteNum = attachDict['GoodsNum']) else: modCoin.GainCoin(optId, attachDict['GoodsId'], attachDict['GoodsNum'], classMethod, param) attachDict['EquipId'] = 0 #更新附件 self.db.update('tb_mail_con', {'Attachment': ''}, 'MailConId=%s'%mailConId) return attachDicts return 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
def CreateUser(self, para={'NickName': '', 'UserCamp': 0}): '''创建用户默认数据 #**param获取用户自定义的昵称,阵营等信息 ''' import random optId = 10002 buildCfg = Gcore.loadCfg(CFG_BUILDING) userCamp = para['UserCamp'] if userCamp == 0: userCamp = random.randint(1, 3) #1:魏,2:蜀,3:吴 ctime = Gcore.common.datetime() data = {'CreateTime':ctime,'GoldCoin':buildCfg['InitGoldCoin'],\ 'WorkerNumber':buildCfg['InitWorkerNum'],'UserHonour':0,\ 'VipLevel':0,'NickName':para['NickName'],\ 'UserCamp':userCamp,'UserIcon':para.get('UserIcon',1),\ 'AccountId':para.get('TotalServiceId',0),\ 'OldAccount':para.get('OldAccount'), 'ProtectEndTime':time.time()-5 } UserId = self.db.insert('tb_user', data) self.uid = UserId playerMod = Gcore.getMod('Player', UserId) #此处会为用户获取新的连接 playerMod.initUser() #是否选择推荐阵营 if userCamp == int(para.get('RCKey', 0)): playerMod.sendCampGift(optId, userCamp) #发放奖励 return UserId
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]
def BuyActPoint(self, para={}): '''购买行动点数''' optId = 91004 MaxBuyActTimes = Gcore.loadCfg(9101).get('MaxBuyActTimes') TodayBuyTimes = self.mod.getTodayBuyTimes() print 'TodayBuyTimes', TodayBuyTimes if MaxBuyActTimes <= TodayBuyTimes: Gcore.out(optId, -91004001) #已达可购买上限 else: TodayBuyTimes += 1 CostValue = Gcore.loadCfg(9101).get('BuyTimesPrice').get( str(TodayBuyTimes)) if CostValue is None: CostValue = max( Gcore.loadCfg(9101).get('BuyTimesPrice').values()) #开始支付 modCoin = Gcore.getMod('Coin', self.uid) pay = modCoin.PayCoin(optId, 1, CostValue, 'WarUI.BuyActTimes', para) if pay < 0: return Gcore.error(optId, -91004995) #支付失败 else: result = self.mod.buyActPoint() if not result: return Gcore.error(optId, -91004002) #系统错误 body = {} body['CanBuy'] = 1 if TodayBuyTimes < MaxBuyActTimes else 0 RestPoint, MaxPoint = self.mod.getActPoint() body['RestPoint'] = RestPoint body['MaxPoint'] = MaxPoint return Gcore.out(optId, body)
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)
def stripEquip(self, General, EquipPart): '''将武将某个部位的装备脱下来''' EquipMap = {1:"HelmetId",2:"ArmourId",3:"WeaponId",4:"SashId",5:"BootsId",6:"JewelryId"} Equipwearing = General.get(EquipMap.get(EquipPart)) if not Equipwearing: return -1 #错误的请求:装备部位不正确或该武将在该部位上没有装备,无法脱下。 modBag = Gcore.getMod('Bag', self.uid) stat = modBag.moveEquip(add=Equipwearing) print '向背包中增加装备', Equipwearing, ('成功' if stat else '失败'), stat if not stat: return -2 #向背包中增加装备失败 Equipwearing = self.db.out_fields(self.tb_equip(), '*', 'UserId=%s AND EquipId=%s' % (self.uid, Equipwearing)) # 脱装备 # + 减少武将属性 General['ForceValue'] -= Equipwearing['EnhanceForce'] General['WitValue'] -= Equipwearing['EnhanceWit'] General['SpeedValue'] -= Equipwearing['EnhanceSpeed'] General['LeaderValue'] -= Equipwearing['EnhanceLeader'] General[EquipMap[EquipPart]] = 0 print '武将脱装备', EquipMap[EquipPart] # + 更新武将表 self.updateGeneralById(General, General['GeneralId']) # + 装备状态 self.db.update(self.tb_equip(), {"EquipStatus":1, "GeneralId":0}, 'UserId=%s AND EquipId=%s' % (self.uid, Equipwearing['EquipId'])) return 1
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)
def offCacheGeneral(self): #布防的武将 '''缓存布防的武将''' WallGenerals = self.db.out_rows('tb_wall_general', '*', \ 'UserId=%s'%self.uid) RetDic = {} if WallGenerals: #没有布防,直接返回。 modGeneral = Gcore.getMod('General', self.uid) WallGeneralList = [g["GeneralId"] for g in WallGenerals] fields = ['GeneralId', 'GeneralType', 'GeneralLevel', 'ForceValue', \ 'WitValue', 'LeaderValue', 'SpeedValue', 'TakeTypeDefense','TakeType','ExpValue'] #获取武将的最新信息 Generals = modGeneral.getLatestGeneralInfo( GeneralIds=WallGeneralList) for General in Generals: for WallGeneral in WallGenerals: if General['GeneralId'] == WallGeneral['GeneralId']: General['x'] = WallGeneral['x'] General['y'] = WallGeneral['y'] General.pop('ExpValue', None) RetDic[General['GeneralId']] = General Gcore.redisL.hset('sgGeneralOnDefense', '%s.%s' % (self.serverid, self.uid), self.encode(RetDic)) Gcore.redisM.hset('sgGeneralOnDefense', '%s.%s' % (self.serverid, self.uid), self.encode(RetDic))