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)
def sendOtherMail(self, toUserIds=[], goods=[], subject='system', content='system award', mailtype=3): ''' 发带有附件的邮件 ,可用于服务后台发放补偿、奖励 toUserId:UserId列表 ,为空,则发放全服 goods元素 {'GoodsType':,'GoodsId':,'GoodsNum':}列表 ''' sysId = 0 timeStamp = int(time.time()) if not toUserIds: toUserIds = self.db.out_list('tb_user', 'UserId') for i in xrange(0, len(toUserIds), 200): datalist = [] for uid in toUserIds[i:i + 200]: mailConId = self.insMailCon(content, goods) data = { 'FromUserId': sysId, 'Subject': subject, 'ToUserId': uid, 'MailConId': mailConId, 'CreateTime': timeStamp, 'MailUserType': mailtype, } datalist.append(data) self.db.insertmany('tb_mail', datalist) Gcore.push(101, toUserIds)
def insertGifts(self, activityId, awardId): ''' 添加通用礼包记录 @param activityId:活动Id,1首冲2签到3成长4活跃5鸿运6在线 @param awardId:奖励Id,各个活动的奖励配置表的Id @param TimeStamp:获奖时间 ''' day = self.getDeadline(activityId) if day == 0: perm = 1 else: perm = 0 row = { 'UserId': self.uid, 'ActivityId': activityId, 'AwardId': awardId, 'isGet': 0, 'CreateTime': time.time(), 'LimiteTime': day, 'Perm': perm } table = 'tb_activity_gift' res = self.db.insert(table, row) #by qiudx 属于通用礼包的将推送给前端 if res: activitys = Gcore.getCfg('tb_cfg_act').values() actIdList = [ activity['ActivityId'] for activity in activitys if activity['GeneralShow'] == 1 ] #print actIdList if activityId in actIdList: num = self.pushGiftNum() Gcore.push(109, self.uid, {'GiftNum': num}) return res
def AgreeApply(self, p={}): ''' :同意申请 ''' optId = 15070 userId = p.get('UserId') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId, -15070901) #外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId, -15070920) #军团不存在 memberNum = self.mod.getClubMemberNum(clubId) if memberNum.get('CurNum') >= memberNum.get('MaxNum'): return Gcore.error(optId, -15070001) #军团成员已满 if self.uid == userId: return Gcore.error(optId, -15070998) #对自己操作,非法权限 memberInfo = self.mod.getMemberInfo(clubId, userId) if not memberInfo: return Gcore.error(optId, -15070002) #没有申请记录 elif memberInfo.get('MemberState') != 0 and memberInfo.get( 'MemberState') != 4: return Gcore.error(optId, -15070996) #操作失败 self.mod.agreeApply(optId, clubId, userId) Gcore.setUserData(userId, {'ClubId': clubId}) #成员被允许加入,更新的军团信息 Gcore.push(113, userId, {'ClubId': clubId}) #推送军团ID recordData = {'uid': userId, 'ValType': 0, 'Val': 1} return Gcore.out(optId, mission=recordData)
def AgreeApply(self,p={}): ''' :同意申请 ''' optId = 15070 userId = p.get('UserId') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId,-15070901)#外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId,-15070920)#军团不存在 memberNum = self.mod.getClubMemberNum(clubId) if memberNum.get('CurNum')>=memberNum.get('MaxNum'): return Gcore.error(optId,-15070001)#军团成员已满 if self.uid == userId: return Gcore.error(optId, -15070998)#对自己操作,非法权限 memberInfo = self.mod.getMemberInfo(clubId,userId) if not memberInfo: return Gcore.error(optId,-15070002)#没有申请记录 elif memberInfo.get('MemberState') != 0 and memberInfo.get('MemberState')!=4: return Gcore.error(optId,-15070996)#操作失败 self.mod.agreeApply(optId, clubId, userId) Gcore.setUserData(userId, {'ClubId':clubId})#成员被允许加入,更新的军团信息 Gcore.push(113,userId,{'ClubId':clubId})#推送军团ID recordData = {'uid':userId,'ValType':0,'Val':1} return Gcore.out(optId,mission=recordData)
def sendAttachment(self, toUserId, goods=[], subject='system', content='system award'): ''' 发带有附件的邮件 toUserId:单人UserId goods元素 {'GoodsType':,'GoodsId':,'GoodsNum':} @return 返回邮件ID ''' sysId = 0 timeStamp = int(time.time()) mailConId = self.insMailCon(content) date = { 'FromUserId': sysId, 'Subject': subject, 'ToUserId': toUserId, 'MailConId': mailConId, 'CreateTime': timeStamp, 'MailUserType': 1 } mailId = self.db.insert('tb_mail', date) if goods != []: for adict in goods: adict['MailId'] = mailId self.db.insertmany('tb_attachment', goods) Gcore.push(101, toUserId) return mailId
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
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: #fields=['FromUserId','ToUserId','Subject','MailConId','CreateTime','MailUserType'] 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.insert_rows('tb_mail',fields,vals) result = self.db.insertmany('tb_mail', vals) Gcore.push(101, toUserIds) return result
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
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
def sendAttachment(self,toUserId,goods=[],subject='system',content='system award'): ''' 发带有附件的邮件 toUserId:单人UserId goods元素 {'GoodsType':,'GoodsId':,'GoodsNum':} @return 返回邮件ID ''' sysId=0 timeStamp=int(time.time()) mailConId=self.insMailCon(content) date={'FromUserId':sysId, 'Subject':subject, 'ToUserId':toUserId, 'MailConId':mailConId, 'CreateTime':timeStamp, 'MailUserType':1} mailId=self.db.insert('tb_mail',date) if goods!=[]: for adict in goods: adict['MailId']=mailId self.db.insertmany('tb_attachment',goods) Gcore.push(101,toUserId) return mailId
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)
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)
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 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 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 pubNotice(self): '''发布消息''' #print 'Stop pubNotice' #return # 暂停发送 delKeys = [] curTime = time.time() for k, row in self.dictNotice.iteritems(): if row['NoticeCycle'] == 0: #不是循环 Channel = self._transToChannel(row['NoticeType']) Gcore.push( 110, [], { 'Channel': Channel, 'Content': row['NoticeContent'], 'Color': row.get('NoticeColor') }) delKeys.append(k) else: #是循环的 if row['NextSentTime'] <= curTime: #print '>>>send',row Channel = self._transToChannel(row['NoticeType']) Gcore.push( 110, [], { 'Channel': Channel, 'Content': row['NoticeContent'], 'Color': row.get('NoticeColor') }) self.dictNotice[k]['NextSentTime'] = curTime + row[ 'NoticeTimeInterval'] * 60 #分钟 for dKey in delKeys: self.dictNotice.pop(dKey, None) #不是循环的从缓存中清除 self.db.update('tb_notice', {'NoticeSent': 1}, 'NoticeId=%s' % dKey)
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 beFighting(self,Fighter,UserId=None): '''被人攻打中''' t = 180 if Gcore.TEST else 180 if not UserId: UserId = self.uid sql = "UPDATE tb_user SET FightEndTime=UNIX_TIMESTAMP()+%s, Fighter='%s' WHERE UserId=%s"%(t,Fighter,UserId) self.db.execute(sql) Gcore.push(105, UserId, {'FightRestTime':t,'Fighter':Fighter}, Type=1) #推送被攻打 print 'ps beFighting',sql
def WarInfo(self,para={}): '''战斗选择界面 @param StoryId: 章节ID ''' optId = 91001 StoryId = para['StoryId'] body = self.mod.getWarDetail(StoryId) Gcore.push(999, self.uid) #测试推送 return Gcore.out(optId, body)
def WarInfo(self, para={}): '''战斗选择界面 @param StoryId: 章节ID ''' optId = 91001 StoryId = para['StoryId'] body = self.mod.getWarDetail(StoryId) Gcore.push(999, self.uid) #测试推送 return Gcore.out(optId, body)
def insFriendShip(self, userId, friendUserId, FriendStatus = 1, isPush = False): '''添加FriendShipStatus为1的好友关系,如果已存在,则更新 相当于重新申请''' row = {'UserId': userId, 'FriendUserId': friendUserId, 'Favor': 0, 'FriendStatus': FriendStatus ,'VisitTime': 0, 'LastChangeTime': int(time.time())} row_check = {'UserId': userId, 'FriendUserId': friendUserId} if isPush: Gcore.push(106,friendUserId) return self.db.insert_update('tb_friend', row, row_check)
def warSweepNew(self, warId, SweepTimes): '''扫荡''' result = {} UserData = self.getUserInfo(['ProcessWarId']) ProcessWarId = UserData['ProcessWarId'] rowStar = self.db.out_fields('tb_war_star', '*', 'UserId=%s' % self.uid) RestPoint, MaxPoint = self.getActPoint() if warId > ProcessWarId or not rowStar.get('War%s' % warId): return False if RestPoint < Gcore.getCfg('tb_cfg_pve', warId, 'ActPointNeed') * SweepTimes: return False else: Gcore.setUserData(self.uid, {'Sweeping': True}) #@todo 自动补兵 for i in xrange(SweepTimes): restTimes = SweepTimes - i - 1 if not Gcore.getUserData(self.uid, 'Sweeping'): #用户落线也会停止 break else: gevent.sleep( Gcore.loadCfg(9101).get('SweepSleep')) #每场间隔3秒 读配置 modBattle = Gcore.getMod('Battle', self.uid, True) initWarResult = modBattle.initWar(warId, 1) #定义为扫荡战役 if not initWarResult: print '初始化战斗失败' break modBattle.getWarInfo() re = modBattle.endBattle({"resultType": 5}) #print '战斗结果',re result[warId] = re #结构不能更改 需要和前台一样 self.warlog(WarId=warId, IsWarSweep=1, Result=re.get('Result', 0)) #@todo 添加更完整战役结果 Gcore.push( 111, self.uid, { 'result': result, 'restPoint': RestPoint, 'restTimes': restTimes }) if not re.get('Result'): break else: RestPoint -= 1 return True
def initMission(self,mIds,userId=None,pushMsg=True): ''' :给玩家添加一个或者多个任务 @param mId:任务Id,一个或者多个 @param userId:用户ID ''' if userId is None: userId = self.uid if not isinstance(mIds, (list, tuple)): mIds = [mIds] tb_m = 'tb_mission' mCfgs = Gcore.getCfg('tb_cfg_mission') now = time.time() insertdata = [] missionCaches = {} pushMids = [] for mid in mIds: data = {'MissionId':mid,'UserId':userId, 'GetValue':0,'Status':1, 'CreateTime':now,'CompleteTime':0} missionCache = {} #处理需要特需处理的任务 getVal = self.getMissionUpdateVal(mid) if getVal: data['GetValue'] = getVal paramB = mCfgs[mid]['ParamB'] if getVal>=paramB:#任务完成 data['GetValue'] = paramB data['Status'] = 3 data['CompleteTime'] = now else: missionCache = {'MissionId':mid,'GetValue':getVal} else: missionCache = {'MissionId':mid,'GetValue':0} if self.db.insert(tb_m,data): insertdata.append(data) pushMids.append(mid) if missionCache:#增加缓存 missionCaches[mid] = missionCache # 更新任务缓存 if missionCaches: activeMission = self._getMissionCache('initMision') activeMission.update(missionCaches) Gcore.setUserData(self.uid, {'ActiveMission':activeMission}) # 推送新任务 if pushMsg and pushMids: Gcore.push(102,self.uid,{'MT':1,'MIDS':pushMids}) return insertdata
def beFighting(self, Fighter, UserId=None): '''被人攻打中''' t = 180 if Gcore.TEST else 180 if not UserId: UserId = self.uid sql = "UPDATE tb_user SET FightEndTime=UNIX_TIMESTAMP()+%s, Fighter='%s' WHERE UserId=%s" % ( t, Fighter, UserId) self.db.execute(sql) Gcore.push(105, UserId, { 'FightRestTime': t, 'Fighter': Fighter }, Type=1) #推送被攻打 print 'ps beFighting', sql
def free(self, uid, sid, ts=None): '''主动释放别人''' if self.serverid == sid: #本服 Data = Gcore.getMod('Building_resource',uid).collectAll() #被释放前,以被占领的身份收集一次 Data['HoldEndTime'] = 0 Gcore.push(112, uid, Data,Type=0) dic = {'HolderId':0,'HolderServerId':0,'HoldEndTime':0} self.db.update('tb_user', dic, 'UserId="%s"' % uid) self.db.execute('DELETE FROM `tb_hold` WHERE GiverId="%s" AND HolderId="%s"' % (uid, self.uid)) self.db.execute('DELETE FROM `tb_hold_log` WHERE UserId="%s"' % uid) self.db.execute('DELETE FROM `tb_hold_revenge` WHERE UserId="%s"' % uid) else: #非本服 Gcore.sendmq(2, sid, {'GiverId':uid}) Gcore.redisM.hdel("sgHold", '%s.%s' % (sid, uid)) return True
def warSweepNew(self,warId,SweepTimes): '''扫荡''' result = {} UserData = self.getUserInfo(['ProcessWarId']) ProcessWarId = UserData['ProcessWarId'] rowStar = self.db.out_fields('tb_war_star','*','UserId=%s'%self.uid) RestPoint,MaxPoint = self.getActPoint() if warId>ProcessWarId or not rowStar.get('War%s'%warId): return False if RestPoint< Gcore.getCfg('tb_cfg_pve',warId,'ActPointNeed')*SweepTimes: return False else: Gcore.setUserData(self.uid, {'Sweeping':True} ) #@todo 自动补兵 for i in xrange(SweepTimes): restTimes = SweepTimes-i-1 if not Gcore.getUserData(self.uid, 'Sweeping'): #用户落线也会停止 break else: gevent.sleep( Gcore.loadCfg(9101).get('SweepSleep') ) #每场间隔3秒 读配置 modBattle = Gcore.getMod('Battle',self.uid,True) initWarResult = modBattle.initWar(warId,1) #定义为扫荡战役 if not initWarResult: print '初始化战斗失败' break modBattle.getWarInfo() re = modBattle.endBattle({"resultType":5}) #print '战斗结果',re result[warId] = re #结构不能更改 需要和前台一样 self.warlog(WarId=warId,IsWarSweep=1,Result=re.get('Result',0)) #@todo 添加更完整战役结果 Gcore.push(111,self.uid,{'result':result,'restPoint':RestPoint,'restTimes':restTimes}) if not re.get('Result'): break else: RestPoint-=1 return True
def pubNotice(self): '''发布消息''' #print 'Stop pubNotice' #return # 暂停发送 delKeys = [] curTime = time.time() for k,row in self.dictNotice.iteritems(): if row['NoticeCycle'] == 0: #不是循环 Channel = self._transToChannel(row['NoticeType']) Gcore.push(110,[],{'Channel': Channel, 'Content':row['NoticeContent'], 'Color':row.get('NoticeColor')}) delKeys.append(k) else: #是循环的 if row['NextSentTime']<=curTime: #print '>>>send',row Channel = self._transToChannel(row['NoticeType']) Gcore.push(110,[],{'Channel': Channel, 'Content':row['NoticeContent'], 'Color':row.get('NoticeColor')}) self.dictNotice[k]['NextSentTime'] = curTime + row['NoticeTimeInterval']*60 #分钟 for dKey in delKeys: self.dictNotice.pop(dKey,None) #不是循环的从缓存中清除 self.db.update('tb_notice',{'NoticeSent':1},'NoticeId=%s'%dKey)
def insFriendShip(self, userId, friendUserId, FriendStatus=1, isPush=False): '''添加FriendShipStatus为1的好友关系,如果已存在,则更新 相当于重新申请''' row = { 'UserId': userId, 'FriendUserId': friendUserId, 'Favor': 0, 'FriendStatus': FriendStatus, 'VisitTime': 0, 'LastChangeTime': int(time.time()) } row_check = {'UserId': userId, 'FriendUserId': friendUserId} if isPush: Gcore.push(106, friendUserId) return self.db.insert_update('tb_friend', row, row_check)
def updateMissions(self,mData): '''更新多个任务(更新相应的任务缓存数据) @param mData: {MId:updateData} MId:任务ID,updateData:更新内容 @return: 更新数目 ''' tb_m = 'tb_mission' mCfg = Gcore.getCfg('tb_cfg_mission') activeMission = Gcore.getUserData(self.uid, 'ActiveMission') # print '更新任务信息=>',mData # print '任务缓存信息=>',activeMission pusMId = [] updateNum = 0 for mId in mData: data = mData[mId] getVal = data.get('GetValue',0) paramB = mCfg[mId]['ParamB'] #如果任务完成推送消息 if getVal>=paramB: data['GetValue']=paramB data['Status']=3 data['CompleteTime'] = time.time() pusMId.append(mId) activeMission.pop(mId,None)#任务完成删除缓存任务 elif getVal: activeMission[mId]['GetValue'] = getVal#更新缓存任务信息 if self.db.update(tb_m,data,'UserId=%s AND MissionId=%s'%(self.uid,mId)): updateNum +=1 #更新任务缓存 Gcore.setUserData(self.uid, {'ActiveMission':activeMission}) #推送通知任务完成 if pusMId: print '任务完成',str(pusMId) Gcore.push(102,self.uid,{'MT':2,'MIDS':pusMId}) return updateNum
def DismissMember(self, p={}): ''' :开除成员(团长操作) ''' optId = 15068 userId = p.get('UserId') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId, -15068901) #外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId, -15068920) #军团不存在 clubLeader = self.mod.getClubLeader(clubId) if self.uid != clubLeader.get('UserId') or self.uid == userId: return Gcore.error(optId, -15068998) #非法权限 userClubId = self.mod.getUserClubId(userId) if userClubId != clubId: return Gcore.error(optId, -15068002) #该用户非军团成员 self.mod.dismissMember(optId, clubId, userId) Gcore.setUserData(userId, {'ClubId': 0}) #更新被开除成员的军团信息 Gcore.push(113, userId, {'ClubId': 0}) #推送军团ID return Gcore.out(optId)
def DismissMember(self,p={}): ''' :开除成员(团长操作) ''' optId = 15068 userId = p.get('UserId') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId,-15068901)#外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId,-15068920)#军团不存在 clubLeader = self.mod.getClubLeader(clubId) if self.uid != clubLeader.get('UserId') or self.uid == userId: return Gcore.error(optId,-15068998)#非法权限 userClubId = self.mod.getUserClubId(userId) if userClubId != clubId: return Gcore.error(optId,-15068002)#该用户非军团成员 self.mod.dismissMember(optId, clubId, userId) Gcore.setUserData(userId, {'ClubId':0})#更新被开除成员的军团信息 Gcore.push(113,userId,{'ClubId':0})#推送军团ID return Gcore.out(optId)
def insertGeneralInteract(self,friendUserId,generalId,mcoinNum): ''' 添加武将交流记录 @param friendUserId: @param generalId: @param mcoinNum: ''' now=Gcore.common.nowtime() row={'UserId':self.uid, 'GeneralId':generalId, 'GeneralUserId':friendUserId, 'McoinNum':mcoinNum, 'interactTime':now, 'isGet':0} re=self.db.insert('tb_interact_general',row) where='isGet=0 AND GeneralId=%s AND GeneralUserId=%s'%(generalId,friendUserId) if self.db.out_field('tb_interact_general','count(1)',where)==1: Gcore.push(104,friendUserId,{'InteractGid':generalId}) return re
def sendOtherMail(self, toUserIds = [], goods = [], subject = 'system', content = 'system award', mailtype = 3): ''' 发带有附件的邮件 ,可用于服务后台发放补偿、奖励 toUserId:UserId列表 ,为空,则发放全服 goods元素 {'GoodsType':,'GoodsId':,'GoodsNum':}列表 ''' sysId = 0 timeStamp = int(time.time()) if not toUserIds: toUserIds = self.db.out_list('tb_user', 'UserId') for i in xrange(0, len(toUserIds), 200): datalist = [] for uid in toUserIds[i: i + 200]: mailConId = self.insMailCon(content, goods) data = {'FromUserId': sysId, 'Subject': subject, 'ToUserId': uid, 'MailConId': mailConId, 'CreateTime': timeStamp, 'MailUserType': mailtype, } datalist.append(data) self.db.insertmany('tb_mail', datalist) Gcore.push(101, toUserIds)
def setHold(self, PeerUID, PeerSID): '''设置别人成为藩国''' #根据配置得出自动解除的天 HoldConfig = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD) RemoveRatio = HoldConfig['RemoveRatio'] d = None for ind in range(1, len(RemoveRatio) + 1, 1): r = random.random() if r <= RemoveRatio[str(ind)]: d = ind break #初始化元数据 BeginTime = int(time.time()) #开始时间 EndTime = BeginTime + int(d * 24 * 60 * 60) #预计结束时间(自动解除时间) # + StopTime是真正结束的时间:默认是EndTime # + LastCollectTime是最近一次奴隶的自动收集资源时间 StopTime, LastCollectTime = EndTime, BeginTime Jcoin, Gcoin = 0, 0 #奴隶的贡献 print '是否是本服', PeerSID == self.serverid, PeerSID, self.serverid if PeerSID == self.serverid: #本服 print '本服' pMod = Gcore.getMod('Player', PeerUID) protectHoldEndTime = pMod.getUserInfo('ProtectHoldEndTime') if BeginTime < protectHoldEndTime: return -1 #对方处于保护时间内,设置失败add by qiudx Data = Gcore.getMod('Building_resource',PeerUID).collectAll() #将地里的资源以自由身的身份收集一次 Data['HoldEndTime'] = EndTime if not Gcore.TEST else int(time.time()+180) Data['HolderName'] = Gcore.getUserData(self.uid,'NickName') Data['GiveRatio'] = Gcore.loadCfg(1506).get('GiveRatio',0.05) Gcore.push(112, PeerUID, Data,Type=1) # + 更新用户表 arr = {'HolderId':self.uid,'HolderServerId':self.serverid,'HoldEndTime':EndTime} self.db.update('tb_user', arr, 'UserId=%s' % PeerUID) # + 插入本服藩国记录 arr = {"HolderId":self.uid, "GiverId":PeerUID, "LastCollectTime":LastCollectTime, "JcoinGive":Jcoin, "GcoinGive":Gcoin, "StopTime":StopTime, "BeginTime": BeginTime, "EndTime":EndTime} #self.db.insert('tb_hold', arr) self.db.insert_update('tb_hold', arr, {"GiverId":PeerUID} ) # + 插入纳贡记录 arr = {"UserId":PeerUID, "HolderId":self.uid, "Gcoin":0, "HolderServerId":self.serverid, "Jcoin":0, "LastGiveTime":BeginTime} self.db.insert_update('tb_hold_log', arr, {"UserId":PeerUID} ) # + 插入藩国反抗记录 date = datetime.date.strftime(datetime.date.fromtimestamp(BeginTime), "%Y-%m-%d") arr = {"UserId":PeerUID, "HolderId":self.uid, "HolderServerId":self.serverid, "ProcessTotal":0, "RevengeCount":0, "LastRevengeDate":date} self.db.insert_update('tb_hold_revenge', arr, {"UserId":PeerUID} ) else: #非本服,发消息 peerKey = Gcore.redisKey(PeerUID) protectHoldEndTime = Gcore.redisM.hget('sgProtectHold', peerKey) if BeginTime < protectHoldEndTime: return -1 #潘国保护时间内,设置失败 Gcore.sendmq(1, PeerSID, {'HolderId':self.uid, 'HolderServerId':self.serverid, 'GiverId':PeerUID, 'EndTime':int(EndTime)}) k = '%s.%s' % (PeerSID, PeerUID) v = '%s.%s.%s.%s.%s.%s' % (self.serverid, self.uid, BeginTime, StopTime, EndTime, LastCollectTime) Gcore.redisM.hset('sgHold', k, v) #货币相关已独立出来 by Lizr k += Gcore.redisKey(self.uid) Gcore.redisM.hset('sgHoldJcoin', k, 0) #1.1008.2.1001 前面是进贡的人 后面的纳贡的人 Gcore.redisM.hset('sgHoldGcoin', k, 0) return True
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 say(self, optId, channel, content, toName = None): #fields = ['NickName', 'VipLevel', 'UserCamp', 'UserLevel'] #playInfo = self.getUserInfo(fields) channel_list = Gcore.loadCfg(CFG_CHANNEL)['Channel'] if channel in channel_list: forbiddenEndTime = self.db.out_field('tb_forbidden_chat', 'ForbiddenEndTime', 'Userid=%s'%self.uid) if forbiddenEndTime and forbiddenEndTime > int(time.time()): return -8 playInfo = Gcore.StorageUser.get(self.uid) if channel not in (5, 6, 7, 8, 9): if self.isLimitTime(self.getUserInfo('UserLevel'), channel): return -1 #聊天间隔限制 msgBody = filterInput(content,i_Min = 1, i_Max = 90, b_Replace = True,b_chat = True) else: msgBody = content #管理员发布的消息不进行过滤 if not msgBody or int == type(msgBody): return -2 #消息未通过验证 if channel == 1: #世界 users=[k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data={'PlayerId':self.uid, 'Channel':channel, 'Content':msgBody, 'PlayerName':playInfo['NickName'], 'VIP':playInfo['VipLevel']} elif channel == 2: #势力 users = [ k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['UserCamp'] == self.getUserCamp() ] data = {'PlayerId':self.uid,'Channel':channel,'Content':msgBody,'PlayerName':playInfo['NickName'],'VIP':playInfo['VipLevel']} elif channel == 3: #军团 if not playInfo['ClubId'] or playInfo['ClubId'] == 0: return -5 users = [ k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['ClubId'] == playInfo['ClubId'] ] data={'PlayerId':self.uid,'Channel':channel,'Content':msgBody,'PlayerName':playInfo['NickName'],'VIP':playInfo['VipLevel']} elif channel == 4: #私聊 if playInfo and toName == playInfo['NickName']: return -6 users = [k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['NickName'] == toName and k != self.uid] if not users: return -3 touserId = users[0] users.append(self.uid) print 'Users',users data = {'PlayerId':self.uid,'Channel':channel,'Content':msgBody,'PlayerName':playInfo['NickName'],'ToName':toName,'ToUserId':touserId} elif channel == 5: #系统 users = [k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data = {'PlayerId':0,'Channel':channel,'Content':msgBody} elif channel == 6: #喇叭 users = [k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data = {'PlayerId':self.uid,'Channel':channel,'Content':msgBody,'PlayerName':playInfo['NickName'],'VIP':playInfo['VipLevel']} modItem = Gcore.getMod('Item',self.uid) re = modItem.useItem(optId, 'say', {}, 801) #if not Gcore.TEST and re < 0: if re < 0: return -4 elif channel == 7: #GM发布公告 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布公告 users = [k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data = {'Channel':channel, 'Content':msgBody} elif channel == 8: #活动 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布活动消息 users = [k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data = {'Channel':channel, 'Content':msgBody} elif channel == 9: #广播 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布广播 users = [k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel')] data = {'Channel':channel, 'Content':msgBody} else: return -5 Gcore.push(110, users, data) self.lastspeaktime = time.time() return data
def say(self, optId, channel, content, toName=None): #fields = ['NickName', 'VipLevel', 'UserCamp', 'UserLevel'] #playInfo = self.getUserInfo(fields) channel_list = Gcore.loadCfg(CFG_CHANNEL)['Channel'] if channel in channel_list: forbiddenEndTime = self.db.out_field('tb_forbidden_chat', 'ForbiddenEndTime', 'Userid=%s' % self.uid) if forbiddenEndTime and forbiddenEndTime > int(time.time()): return -8 playInfo = Gcore.StorageUser.get(self.uid) if channel not in (5, 6, 7, 8, 9): if self.isLimitTime(self.getUserInfo('UserLevel'), channel): return -1 #聊天间隔限制 msgBody = filterInput(content, i_Min=1, i_Max=90, b_Replace=True, b_chat=True) else: msgBody = content #管理员发布的消息不进行过滤 if not msgBody or int == type(msgBody): return -2 #消息未通过验证 if channel == 1: #世界 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = { 'PlayerId': self.uid, 'Channel': channel, 'Content': msgBody, 'PlayerName': playInfo['NickName'], 'VIP': playInfo['VipLevel'] } elif channel == 2: #势力 users = [ k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['UserCamp'] == self.getUserCamp() ] data = { 'PlayerId': self.uid, 'Channel': channel, 'Content': msgBody, 'PlayerName': playInfo['NickName'], 'VIP': playInfo['VipLevel'] } elif channel == 3: #军团 if not playInfo['ClubId'] or playInfo['ClubId'] == 0: return -5 users = [ k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['ClubId'] == playInfo['ClubId'] ] data = { 'PlayerId': self.uid, 'Channel': channel, 'Content': msgBody, 'PlayerName': playInfo['NickName'], 'VIP': playInfo['VipLevel'] } elif channel == 4: #私聊 if playInfo and toName == playInfo['NickName']: return -6 users = [k for k in Gcore.StorageUser\ if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') and Gcore.StorageUser[k]['NickName'] == toName and k != self.uid] if not users: return -3 touserId = users[0] users.append(self.uid) print 'Users', users data = { 'PlayerId': self.uid, 'Channel': channel, 'Content': msgBody, 'PlayerName': playInfo['NickName'], 'ToName': toName, 'ToUserId': touserId } elif channel == 5: #系统 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = {'PlayerId': 0, 'Channel': channel, 'Content': msgBody} elif channel == 6: #喇叭 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = { 'PlayerId': self.uid, 'Channel': channel, 'Content': msgBody, 'PlayerName': playInfo['NickName'], 'VIP': playInfo['VipLevel'] } modItem = Gcore.getMod('Item', self.uid) re = modItem.useItem(optId, 'say', {}, 801) #if not Gcore.TEST and re < 0: if re < 0: return -4 elif channel == 7: #GM发布公告 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布公告 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = {'Channel': channel, 'Content': msgBody} elif channel == 8: #活动 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布活动消息 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = {'Channel': channel, 'Content': msgBody} elif channel == 9: #广播 userType = self.getUserInfo('UserType') if userType != 1: return -7 #非GM不允许发布广播 users = [ k for k in Gcore.StorageUser if Gcore.StorageUser[k] and Gcore.StorageUser[k].get('Channel') ] data = {'Channel': channel, 'Content': msgBody} else: return -5 Gcore.push(110, users, data) self.lastspeaktime = time.time() return data