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 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 WarInfoAll(self, para={}): '''战役主界面(新) by Lizr''' optId = 91003 body = self.mod.getWarInfoAll() RestPoint, MaxPoint = self.mod.getActPoint() body['RestPoint'] = RestPoint body['MaxPoint'] = MaxPoint body['PerBuyAddPoint'] = Gcore.loadCfg(9101).get('PerBuyAddPoint') body['BuyTimesPrice'] = Gcore.loadCfg(9101).get('BuyTimesPrice') MaxBuyActTimes = Gcore.loadCfg(9101).get('MaxBuyActTimes') TodayBuyTimes = self.mod.getTodayBuyTimes() body['CanBuy'] = 1 if TodayBuyTimes < MaxBuyActTimes else 0 body['AlreadyBuyTimes'] = TodayBuyTimes body['MaxBuyActTimes'] = MaxBuyActTimes return Gcore.out(optId, body)
def WarInfoAll(self,para={}): '''战役主界面(新) by Lizr''' optId = 91003 body = self.mod.getWarInfoAll() RestPoint,MaxPoint = self.mod.getActPoint() body['RestPoint'] = RestPoint body['MaxPoint'] = MaxPoint body['PerBuyAddPoint'] = Gcore.loadCfg(9101).get('PerBuyAddPoint') body['BuyTimesPrice'] = Gcore.loadCfg(9101).get('BuyTimesPrice') MaxBuyActTimes = Gcore.loadCfg(9101).get('MaxBuyActTimes') TodayBuyTimes = self.mod.getTodayBuyTimes() body['CanBuy'] = 1 if TodayBuyTimes < MaxBuyActTimes else 0 body['AlreadyBuyTimes'] = TodayBuyTimes body['MaxBuyActTimes'] = MaxBuyActTimes return Gcore.out(optId, body)
def GetSignInLog(self, param={}): '''获取签到日志''' optId = 23006 data = self.mod.getSigninLog() a = list(data['SignInDate']) data['SignInDate'] = ','.join(a) #获取全勤奖励信息 awards = Gcore.getCfg('tb_cfg_act_signin_award').values() fullWorkAwards = filter(lambda dic:dic['AwardId']>=3000 and dic['AwardId']<4000, awards) now = datetime.datetime.now() data['FullWorkAwardId'] = fullWorkAwards[now.month-1]['AwardId'] #获取周期奖励信息 finalAwards = Gcore.loadCfg(CFG_ACT_SIGNIN)['FinalAwardId'] #awards = finalAwards.split(',') awards = finalAwards signCount = data['SignInCount'] n = signCount / 30 % len(awards) if signCount % 30 == 0: n -= 1 awardId = int(awards[n]) data['FinalAwardId'] = awardId signCount = signCount % 30 data['SignInDays'] = signCount if signCount else 30 #用于前台显示当前周期内的天数,30天一周期 data['Refill'] = 5 - data['Refill'] return Gcore.out(optId, data)
def getDefeaters(self, TimeStamp=None): """获取手下败将""" TimeStamp = TimeStamp if TimeStamp else time.time() HoldConfig = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD) ExpireTime = HoldConfig["ExpireTime"] # 过期时间 LimitCnt = HoldConfig["LimitCount"] # 手下败将的最大个数 table = "tb_battle_record" fields = [ "PeerUID", "PeerSID", "PeerName", "PeerVipLevel", "PeerCamp", "PeerIcon", "PeerLevel", "MAX(CreateTime) as CreateTime", ] where = """UserId="%s" AND BattleResult=1 AND CreateTime>="%s" AND BattleType=1 GROUP BY UserId, PeerUID, PeerSID LIMIT %s""" % ( self.uid, TimeStamp - ExpireTime, LimitCnt, ) res = self.db.out_rows(table, fields, where) return res
def refreashTime(self): '''更新操作时间和当日在线时间(玩家登出时要调用)''' now = Gcore.common.nowtime() #today=datetime.date.today() #t0=time.mktime(today.timetuple()) lastLottery = self.getOnlineLottery() lastChangeTime = lastLottery['LastChangeTime'] modPlayer = Gcore.getMod('Player', self.uid) lastLoginTime = modPlayer.getUserBaseInfo(['LastLoginTime' ])['LastLoginTime'] tt = max(lastChangeTime, lastLoginTime) addTime = now - tt #if lastChangeTime<t0: if time.localtime(lastChangeTime)[2] != time.localtime(now)[2]: lastLottery['DayOnlineTime'] = 0 lastLottery['LotteryCount'] = 0 #timeCfg = Gcore.getCfg('tb_cfg_act_online_limit') timeCfg = Gcore.loadCfg(CFG_ACT_ONLINE_LIMIT) maxt = 0 for t in timeCfg.values(): #maxt += t['NeedTime']#获取最大次数所需要时间 maxt += t lastLottery['DayOnlineTime'] = min(lastLottery['DayOnlineTime'] + addTime, maxt) #最大时间不能超过上限 lastLottery['LastChangeTime'] = now #更新操作时间 where = 'UserId=%s' % self.uid self.db.update('tb_activity_online', lastLottery, where)
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 gainDeveote(self,clubId,gainWay,**p): ''' :获得贡献 @param clubId: @param gainWay:获得方式 1贡献 3抽奖 @param p:if gainWay==1: p{coinValue,coinType} elif gainWay==3: p{devoteNum} ''' if not clubId: return 0 devoteNum = p.get('devoteNum',0) record = {'ClubId':clubId,'UserId':self.uid, 'UserType':Gcore.getUserData(self.uid,'UserType'), 'ActionType':gainWay,'DevoteNum':devoteNum, 'CreateTime':time.time()} if gainWay==1:#贡献获得 coinType = p['coinType'] coinValue = p['coinValue'] devoteBase = Gcore.loadCfg(defined.CFG_BUILDING_CLUB).get('ClubGiveBase').get( str(coinType)) devoteNum = coinValue/devoteBase record['DevoteNum'] = devoteNum record['DevoteCoinType'] = coinType record['DevoteCoinValue'] = coinValue sql = 'UPDATE tb_club_member \ SET DevoteCurrent=DevoteCurrent+%s,\ DevoteTotal=DevoteTotal+%s \ WHERE UserId=%s AND ClubId=%s'%(devoteNum,devoteNum,self.uid,clubId) if self.db.execute(sql): self.db.insert('tb_log_club_devote',record) return devoteNum else: 0
def login(self, loginIp=None, loginMode=None): '''登入时调用的方法''' now = time.time() sql = "UPDATE tb_user SET LastLoginTime=UNIX_TIMESTAMP(),Online=1,LoginTimes=LoginTimes+1 WHERE UserId=%s" % self.uid self.db.execute(sql) #if not self.uid in Gcore.StorageUser: #缓存基础用户信息 if 1: # fixed by zhoujingjiang self.cacheUserData(self.uid) UserType = Gcore.getUserData(self.uid, 'UserType') #添加登录日志 # loginLogTB = 'tb_log_login201306' loginLogTB = self.tb_log_login() data = { 'UserId': self.uid, 'LoginTime': now, 'UserType': UserType, 'LoginModel': loginMode, 'LoginIP': loginIp } self.logId = self.db.insert(loginLogTB, data) print self.uid, 'login get logId:%s at %s' % (self.logId, now) key = Gcore.redisKey(self.uid) Gcore.redisM.hset('sgLogin', key, '1') UserLevel = self.getUserLevel() modActivity = Gcore.getMod('Activity', self.uid) modActivity.signin(0, '') if UserLevel >= Gcore.loadCfg(9301).get('FightLevel'): row = {} row['Online'] = 1 row['UserId'] = self.uid
def getRankReward(self): '''获取排名奖励界面''' data = {} data['RewardTime'] = Gcore.loadCfg(Gcore.defined.CFG_RANK_FIGHT).get('RewardTime','22:00:00') RankId = self.db.out_field('tb_rank_fight_last','RankId','UserId=%s'%self.uid) data['RewardRankId'] = RankId if RankId else 0 cfg_rank_reward = Gcore.getCfg('tb_cfg_rank_reward') data['RewardBoxList'] = {} MyRewardRankId = data['RewardRankId'] for k,v in cfg_rank_reward.iteritems(): data['RewardBoxList'][k] = { 'RewardId':v['RewardId'], 'RankFrom':v['RankFrom'], 'RankTo':v['RankTo'], 'Bright':1 if v['RankFrom']<=MyRewardRankId<=v['RankTo'] else 0 } data['RewardBoxList'][k]['Rewards'] = [] for i in xrange(1,6): field1 = 'RewardType%s'%i field2 = 'GoodsId%s'%i field3 = 'GoodsNum%s'%i if v[field1] and v[field2]: cell = {'RewardType':v[field1], 'GoodsId':v[field2], 'GoodsNum':v[field3]} data['RewardBoxList'][k]['Rewards'].append(cell) return data
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 GetCrewList(self,p={}): '''查询军团成员列表/申请列表 @param ListView: 1:成员列表2:申请列表 ''' optId = 15073 listView = p['ListView'] pageNum = p['PageNum'] sortWay = 'ASC' if p['SortWay']==0 else 'DESC' sortField = p['SortField'] if sortField == 1: sortField = 'u.VipLevel '+sortWay elif sortField == 2: sortField = 'm.DevoteTotal '+sortWay else: sortField = 'u.UserHonour '+sortWay clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId,-15066920)#军团不存在 pageSize = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB ).get('MemPS') memberNum = self.mod.getCrewNum(listView,clubId) maxPage = int(math.ceil(float(memberNum)/pageSize)) if 0<maxPage<pageNum: pageNum = maxPage if pageNum<1: pageNum = 1 offset = (pageNum-1)*pageSize # end = offset+pageSize if memberNum>0: members = self.mod.getCrewList(listView,clubId,sortField,offset,pageSize) else: members = [] clubLevel = self.mod.getClubInfo(clubId).get('ClubLevel') memberNum = self.mod.getClubMemberNum(clubId) return Gcore.out(optId,{'ClubLevel':clubLevel,'MemberNum':memberNum,'Members':members,'PageNum':pageNum,'MaxPage':maxPage})
def ModifyClub(self,p={}): ''' :修改军团信息(团长) ''' optId = 15065 logoId = p.get('LogoId') clubNotice = p.get('ClubNotice') allowState = p.get('AllowState') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId,-15065901)#外史院建筑不存在 cfgClub = Gcore.loadCfg(defined.CFG_BUILDING_CLUB) noticeLimit = cfgClub.get('ClubNoticeLimit') flag = com.filterInput(clubNotice,0,noticeLimit) if flag == -1: return Gcore.error(optId, -15065993) #长度不符合要求 elif flag == -2: return Gcore.error(optId, -15065992) #不能含有敏感字符 if logoId not in range(1,7): return Gcore.error(optId,-15065999)#参数错误 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId,-15065920)#军团不存在 clubLeader = self.mod.getClubLeader(clubId) if self.uid != clubLeader.get('UserId'): return Gcore.error(optId,-15065998)#非法权限 data = {'ClubLogoId':logoId,'ClubNotice':clubNotice,'AllowState':allowState} self.mod.modifyClub(clubId,data) return Gcore.out(optId,data)
def getActPoint(self): '''获得 剩余行动点数/最大行动点数''' BuyActPoint = self.getUserInfo('BuyActPoint') row = self._lastActRecord() MaxPoint = Gcore.getCfg('tb_cfg_action_point',self.getUserLevel(),'ActPoint') if not row: RestPoint = MaxPoint + BuyActPoint else: nowtime = Gcore.common.nowtime() PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime',1200) if Gcore.TEST and self.uid in [1001,43953]: PerIncrTime = testPerIncrTime if row['ActPoint']>=MaxPoint: #已满,不恢复 RestPoint = row['ActPoint'] else: AccuTime = row['AccuTime'] + ( nowtime - row['LastWarTime'] ) incrTimes = AccuTime//PerIncrTime #回复一点需要多长时间 20分钟 #print 'incrTimes',incrTimes print 'getActPoint.上次剩余',row['ActPoint'] print 'getActPoint.至已经恢复了',incrTimes ActPoint = row['ActPoint'] + incrTimes if ActPoint > MaxPoint: ActPoint = MaxPoint print 'getActPoint.剩余+累计越出上限,设为上限',ActPoint #查看的时候 不更新累计时间 tb_war_action.AccuTime RestPoint = ActPoint #print '剩余次数 最大次数',RestPoint,MaxPoint, 前台显示的是: 剩余次数/最大次数 return (RestPoint,MaxPoint)
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 MailList(self, param={}): ''' 收件箱/发件箱列表 @param param['MailType']=1 表示收件箱 param['MailType']=2 表示发件箱 ''' optId = 18003 mailType = int(param['MailType']) page = int(param['Page']) #页码 if not page: #默认为第一页 page = 1 if mailType not in (1, 2): return Gcore.error(optId, -18003999) #MailType值不对 mailCfg = Gcore.loadCfg(Gcore.defined.CFG_MAIL) pagePerNum = int(mailCfg['MailShowPerPageMax']) #每页的邮件数 mailCount = int(self.mod.mailCountByType(mailType)) #收件箱/发件箱中邮件总数 mailDatas = self.mod.getMailList(mailType, page, pagePerNum) #每页显示的邮件数据 subjShowMax = mailCfg['SubjectShowMax'] #邮件主题显示最大长度 self.mod.finMailDatas(mailDatas, subjShowMax) totalPage = int(math.ceil(1.0 * mailCount / pagePerNum)) body = { 'mailDatas': mailDatas, 'page': page, 'mailCount': mailCount, 'totalpage': totalPage } return Gcore.out(optId, body=body)
def setReventProcess(self, process, flag=0, TimeStamp=None): '''设置反抗进度:process-攻城进度;flag-0失败,1成功''' #返回值:-2 反抗次数已达到最大 -1 参数错误 0 没达到成功条件 1达到成功条件 if not 0 <= process <=1: return -1 #攻城进度取值范围不对 TimeStamp = TimeStamp if TimeStamp else time.time() cnt, pro = self.calcRevent(TimeStamp) ratio = 0.5 #读配置 maxnum = 5 #读配置 cnt_new = cnt + 1 pro_new = pro + float(ratio * process) #取攻城进度的50%。 if cnt_new > maxnum: return -2 elif pro_new >= 1.0 or flag == 1: #累积进度达到100% ## 读配置 self.db.execute('DELETE FROM `tb_hold_revenge` WHERE UserId="%s"'%self.uid) hsid,huid = self.getMyHolder() if huid: self.freed(huid, hsid) #让自己被释放 pMod = Gcore.getMod('Player', self.uid) protectTime = Gcore.loadCfg(CFG_BUILDING_HOLD)['RvProtectHoldSecond'] pMod.addProtectHoldTime(protectTime) return 1 else: #增加累计进度 arr = {} arr['ProcessTotal'] = pro_new arr['RevengeCount'] = cnt_new arr['LastRevengeDate'] = datetime.date.strftime( datetime.date.fromtimestamp(TimeStamp), '%Y-%m-%d') self.db.update('tb_hold_revenge', arr, 'UserId="%s"'%self.uid)
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 GetSignInLog(self, param={}): '''获取签到日志''' optId = 23006 data = self.mod.getSigninLog() a = list(data['SignInDate']) data['SignInDate'] = ','.join(a) #获取全勤奖励信息 awards = Gcore.getCfg('tb_cfg_act_signin_award').values() fullWorkAwards = filter( lambda dic: dic['AwardId'] >= 3000 and dic['AwardId'] < 4000, awards) now = datetime.datetime.now() data['FullWorkAwardId'] = fullWorkAwards[now.month - 1]['AwardId'] #获取周期奖励信息 finalAwards = Gcore.loadCfg(CFG_ACT_SIGNIN)['FinalAwardId'] #awards = finalAwards.split(',') awards = finalAwards signCount = data['SignInCount'] n = signCount / 30 % len(awards) if signCount % 30 == 0: n -= 1 awardId = int(awards[n]) data['FinalAwardId'] = awardId signCount = signCount % 30 data[ 'SignInDays'] = signCount if signCount else 30 #用于前台显示当前周期内的天数,30天一周期 data['Refill'] = 5 - data['Refill'] return Gcore.out(optId, data)
def login(self,loginIp=None,loginMode=None): '''登入时调用的方法''' now = time.time() sql = "UPDATE tb_user SET LastLoginTime=UNIX_TIMESTAMP(),Online=1,LoginTimes=LoginTimes+1 WHERE UserId=%s"%self.uid self.db.execute(sql) #if not self.uid in Gcore.StorageUser: #缓存基础用户信息 if 1: # fixed by zhoujingjiang self.cacheUserData(self.uid) UserType = Gcore.getUserData(self.uid,'UserType') #添加登录日志 # loginLogTB = 'tb_log_login201306' loginLogTB = self.tb_log_login() data = {'UserId':self.uid,'LoginTime':now,'UserType':UserType, 'LoginModel':loginMode,'LoginIP':loginIp} self.logId = self.db.insert(loginLogTB,data) print self.uid,'login get logId:%s at %s'%(self.logId,now) key = Gcore.redisKey(self.uid) Gcore.redisM.hset('sgLogin',key,'1') UserLevel = self.getUserLevel() modActivity=Gcore.getMod('Activity',self.uid) modActivity.signin(0,'') if UserLevel>=Gcore.loadCfg(9301).get('FightLevel'): row = {} row['Online']=1 row['UserId']=self.uid
def GetMyClub(self,p={}): '''获取我的军团信息 ''' optId = 15062 clubId = self.mod.getUserClubId() clubInfo = {'BaseInfo':0,'MemberNum':0, 'DevoteValue':0,'LeaderInfo':0, 'HasClub':0,'MyInfo':0} if not clubId: return Gcore.out(optId,clubInfo)#没有军团 ClubInfo = self.mod.getClubInfo(clubId)#军团基础信息 #by Lizr 前台没有这些值,,抽取 del ClubInfo['ClubTotalExp'] del ClubInfo['ClubLevelTotalExp'] del ClubInfo['CreatDate'] clubInfo['BaseInfo'] = ClubInfo clubInfo['MemberNum'] = self.mod.getClubMemberNum(clubId)#军团成员数量 clubInfo['DevoteValue'] = self.mod.getTodayDevote(clubId,2)#当天贡献值 clubInfo['LeaderInfo'] = self.mod.getClubLeader(clubId)#团长信息 clubInfo['MyInfo'] = self.mod.getMemberInfo(clubId,self.uid,['DevoteCurrent','DevoteTotal']) clubInfo['HasClub'] = 1 clubInfo['DevoteLogs'] = com.list2dict(self.mod.getDevoteLogs(clubId), 1) clubInfo['DevoteBase'] = Gcore.loadCfg(defined.CFG_BUILDING_CLUB).get('ClubGiveBase') return Gcore.out(optId,clubInfo)
def ModifyClub(self, p={}): ''' :修改军团信息(团长) ''' optId = 15065 logoId = p.get('LogoId') clubNotice = p.get('ClubNotice') allowState = p.get('AllowState') building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId, -15065901) #外史院建筑不存在 cfgClub = Gcore.loadCfg(defined.CFG_BUILDING_CLUB) noticeLimit = cfgClub.get('ClubNoticeLimit') flag = com.filterInput(clubNotice, 0, noticeLimit) if flag == -1: return Gcore.error(optId, -15065993) #长度不符合要求 elif flag == -2: return Gcore.error(optId, -15065992) #不能含有敏感字符 if logoId not in range(1, 7): return Gcore.error(optId, -15065999) #参数错误 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId, -15065920) #军团不存在 clubLeader = self.mod.getClubLeader(clubId) if self.uid != clubLeader.get('UserId'): return Gcore.error(optId, -15065998) #非法权限 data = { 'ClubLogoId': logoId, 'ClubNotice': clubNotice, 'AllowState': allowState } self.mod.modifyClub(clubId, data) return Gcore.out(optId, data)
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 buyActPoint(self, point=0): '''增加行动点数 @param point: 增加的点数''' print 'ps buyActPoint' if not point: point = Gcore.loadCfg(9101).get('PerBuyAddPoint') row = self.recoverActPoint(point, 1) # if row: # todaytime = Gcore.common.today0time() # sql = "UPDATE tb_war_action SET ActPoint=ActPoint+%s WHERE UserId=%s AND LastWarTime>=%s" \ # %(point,self.uid,todaytime) # self.db.execute(sql) #如果今日有打过 就修正累计记录 # print 'buyActPoint',sql sql = "UPDATE tb_user SET BuyActPoint=BuyActPoint+%s WHERE UserId=%s" % ( point, self.uid) AddResult = self.db.execute(sql) try: #可购买上限 sql = "UPDATE tb_log_buy_act SET Times = Times+1 WHERE UserId=%s AND BuyDate = CURDATE()" % self.uid result = self.db.execute(sql) if not result: #无影响行数 sql = "INSERT INTO tb_log_buy_act (UserId,Times,BuyDate) VALUES(%s,1,CURDATE())" % self.uid result = self.db.execute(sql) except: pass finally: return AddResult
def GetMyClub(self, p={}): '''获取我的军团信息 ''' optId = 15062 clubId = self.mod.getUserClubId() clubInfo = { 'BaseInfo': 0, 'MemberNum': 0, 'DevoteValue': 0, 'LeaderInfo': 0, 'HasClub': 0, 'MyInfo': 0 } if not clubId: return Gcore.out(optId, clubInfo) #没有军团 ClubInfo = self.mod.getClubInfo(clubId) #军团基础信息 #by Lizr 前台没有这些值,,抽取 del ClubInfo['ClubTotalExp'] del ClubInfo['ClubLevelTotalExp'] del ClubInfo['CreatDate'] clubInfo['BaseInfo'] = ClubInfo clubInfo['MemberNum'] = self.mod.getClubMemberNum(clubId) #军团成员数量 clubInfo['DevoteValue'] = self.mod.getTodayDevote(clubId, 2) #当天贡献值 clubInfo['LeaderInfo'] = self.mod.getClubLeader(clubId) #团长信息 clubInfo['MyInfo'] = self.mod.getMemberInfo( clubId, self.uid, ['DevoteCurrent', 'DevoteTotal']) clubInfo['HasClub'] = 1 clubInfo['DevoteLogs'] = com.list2dict(self.mod.getDevoteLogs(clubId), 1) clubInfo['DevoteBase'] = Gcore.loadCfg( defined.CFG_BUILDING_CLUB).get('ClubGiveBase') return Gcore.out(optId, clubInfo)
def MailList(self,param={}): ''' 收件箱/发件箱列表 @param param['MailType']=1 表示收件箱 param['MailType']=2 表示发件箱 ''' optId = 18003 mailType = int(param['MailType']) page = int(param['Page']) #页码 if not page: #默认为第一页 page = 1 if mailType not in (1,2): return Gcore.error(optId,-18003999) #MailType值不对 mailCfg = Gcore.loadCfg(Gcore.defined.CFG_MAIL) pagePerNum = int(mailCfg['MailShowPerPageMax']) #每页的邮件数 mailCount = int(self.mod.mailCountByType(mailType)) #收件箱/发件箱中邮件总数 mailDatas = self.mod.getMailList(mailType,page,pagePerNum) #每页显示的邮件数据 subjShowMax = mailCfg['SubjectShowMax'] #邮件主题显示最大长度 self.mod.finMailDatas(mailDatas,subjShowMax) totalPage = int(math.ceil(1.0*mailCount/pagePerNum)) body = {'mailDatas':mailDatas,'page':page,'mailCount':mailCount,'totalpage':totalPage} return Gcore.out(optId, body = body)
def getActPoint(self): '''获得 剩余行动点数/最大行动点数''' BuyActPoint = self.getUserInfo('BuyActPoint') row = self._lastActRecord() MaxPoint = Gcore.getCfg('tb_cfg_action_point', self.getUserLevel(), 'ActPoint') if not row: RestPoint = MaxPoint + BuyActPoint else: nowtime = Gcore.common.nowtime() PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime', 1200) if Gcore.TEST and self.uid in [1001, 43953]: PerIncrTime = testPerIncrTime if row['ActPoint'] >= MaxPoint: #已满,不恢复 RestPoint = row['ActPoint'] else: AccuTime = row['AccuTime'] + (nowtime - row['LastWarTime']) incrTimes = AccuTime // PerIncrTime #回复一点需要多长时间 20分钟 #print 'incrTimes',incrTimes print 'getActPoint.上次剩余', row['ActPoint'] print 'getActPoint.至已经恢复了', incrTimes ActPoint = row['ActPoint'] + incrTimes if ActPoint > MaxPoint: ActPoint = MaxPoint print 'getActPoint.剩余+累计越出上限,设为上限', ActPoint #查看的时候 不更新累计时间 tb_war_action.AccuTime RestPoint = ActPoint #print '剩余次数 最大次数',RestPoint,MaxPoint, 前台显示的是: 剩余次数/最大次数 return (RestPoint, MaxPoint)
def buyActPoint(self,point=0): '''增加行动点数 @param point: 增加的点数''' print 'ps buyActPoint' if not point: point = Gcore.loadCfg(9101).get('PerBuyAddPoint') row = self.recoverActPoint(point,1) # if row: # todaytime = Gcore.common.today0time() # sql = "UPDATE tb_war_action SET ActPoint=ActPoint+%s WHERE UserId=%s AND LastWarTime>=%s" \ # %(point,self.uid,todaytime) # self.db.execute(sql) #如果今日有打过 就修正累计记录 # print 'buyActPoint',sql sql = "UPDATE tb_user SET BuyActPoint=BuyActPoint+%s WHERE UserId=%s"%(point,self.uid) AddResult = self.db.execute(sql) try: #可购买上限 sql ="UPDATE tb_log_buy_act SET Times = Times+1 WHERE UserId=%s AND BuyDate = CURDATE()"%self.uid result = self.db.execute(sql) if not result: #无影响行数 sql = "INSERT INTO tb_log_buy_act (UserId,Times,BuyDate) VALUES(%s,1,CURDATE())"%self.uid result = self.db.execute(sql) except: pass finally: return AddResult
def OnlineLottory(self, param={}): '''在线奖励抽奖''' optId = 23011 self.mod.refreashTime() #更新操作时间 lastLottery = self.mod.getOnlineLottery() #获取可抽奖次数(待) #timeCfg = Gcore.getCfg('tb_cfg_act_online_limit') timeCfg = Gcore.loadCfg(CFG_ACT_ONLINE_LIMIT) dt = lastLottery['DayOnlineTime'] less = 0 lottoryNum = len(timeCfg.keys()) # for i in range(1, len(timeCfg.values())+1): # if dt >= timeCfg[i]['NeedTime']: # less += 1 # dt -= timeCfg[i]['NeedTime'] for i in xrange(1, lottoryNum + 1): if dt >= timeCfg[str(i)]: less += 1 dt -= timeCfg[str(i)] less -= lastLottery['LotteryCount'] if less <= 0: return Gcore.error(optId, -23011001) #可抽奖次数不足 #获取抽到的奖励类型和等级 typeCfg = Gcore.getCfg('tb_cfg_act_online_type').values() typeCfg = filter(lambda dic: dic['Ratio'] != 0, typeCfg) #暂时不随机到宝物和兵书 types = [] level = 3 typeValue = random.randint(2, 3) #如果等级是3则在铜钱和军资中随即一个 for i in range(0, 3): theType = common.Choice(typeCfg) for j in range(0, len(types)): if theType['TypeId'] == types[j]: level -= 1 typeValue = theType['TypeId'] break types.append(theType['TypeId']) #进行奖励 awards = Gcore.getCfg('tb_cfg_act_online_award', (typeValue, level)) award = random.choice(awards) modReward = Gcore.getMod('Reward', self.uid) award['Gain'] = modReward.reward(optId, param, award['AwardType'], award['GoodsId'], award['GoodsNum']) #更新在线奖励记录 lastLottery['AwardId'] = award['AwardId'] lastLottery['LotteryCount'] += 1 lastLottery['AwardType'] = award['AwardType'] lastLottery['GoodsId'] = award['GoodsId'] lastLottery['GoodsNum'] = award['GoodsNum'] types = [str(t) for t in types] lastLottery['LotteryInfo'] = str.join(',', types) self.mod.updateOnlineLottery(lastLottery) return Gcore.out(optId, { 'LotteryInfo': lastLottery['LotteryInfo'], 'Award': award })
def getBagSize(self): ''':查询背包容量''' maxSize = self.db.out_field('tb_bag_expand', 'MAX(ExpandNum)', 'UserId=%s' % self.uid) if maxSize is None: maxSize = Gcore.loadCfg(Gcore.defined.CFG_PLAYER_BAG).get( 'InitNum') #初始格仔数 return maxSize
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 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 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 RankFightInfo(self,para={}): '''比武主界面 和 排名奖励界面 所需数据''' optId = 24001 UserLevel = Gcore.getUserData(self.uid,'UserLevel') OpenLevel = Gcore.loadCfg(2401).get('RankFightOpenLevel') if UserLevel<OpenLevel: return Gcore.error(optId,-24001001) RankFightInfo = self.mod.getRankFightInfo() RankReward = self.mod.getRankReward() return Gcore.out(optId,{'RankFightInfo':RankFightInfo,'RankReward':RankReward})
def validApplyInterval(self): '''验证申请军团时间间隔''' applyInterval = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('ApplyInterval') applyLimitTime = time.time()-applyInterval where = 'UserId=%s AND MemberState=3 AND TimeExit>%s'%(self.uid,applyLimitTime) flag = self.db.out_field('tb_club_member','UserId',where) if flag: return False else: return True
def OpenBox(self, p={}): '''开宝箱''' optId = 15082 boxType = p['BoxType'] boxCfg = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost') boxTypes = [int(i) for i in boxCfg.keys()] if boxType not in boxTypes: return Gcore.error(optId, -15082999) #参数错误 building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId, -15082901) #外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId, -15082920) #军团不存在 #支付贡献 cost = boxCfg.get(str(boxType)) left = self.mod.payDevote(clubId, cost) # left = 1 #支付成功,开始抽奖 if left >= 0: goodsCfg = Gcore.getCfg('tb_cfg_club_box', boxType) lucky = com.Choice(goodsCfg) rType = lucky.get('RewardType') goodsId = lucky['GoodsId'] goodsNum = lucky['GoodsNum'] body = { 'Left': left, 'RewardType': rType, 'GoodsId': goodsId, 'GoodsNum': goodsNum } equipIds = [] # if rType in [1,2,3]:#装备,道具,资源 ids = Gcore.getMod('Reward', self.uid).reward(optId, p, rType, goodsId, goodsNum) if rType == 1: if isinstance(ids, list): equipIds = ids body['EIDS'] = equipIds self.mod.insertBoxLog(clubId, boxType, lucky) body['Logs'] = self.mod.getBoxLogList(1, clubId, offset=0, pageSize=2, timeLimit=False) recordData = {'uid': self.uid, 'ValType': 0, 'Val': 1} #成就,任务记录 return Gcore.out(optId, body, mission=recordData) else: return Gcore.error(optId, -15082002) # 支付失败
def OnlineLottory(self, param={}): '''在线奖励抽奖''' optId = 23011 self.mod.refreashTime()#更新操作时间 lastLottery = self.mod.getOnlineLottery() #获取可抽奖次数(待) #timeCfg = Gcore.getCfg('tb_cfg_act_online_limit') timeCfg = Gcore.loadCfg(CFG_ACT_ONLINE_LIMIT) dt = lastLottery['DayOnlineTime'] less = 0 lottoryNum = len(timeCfg.keys()) # for i in range(1, len(timeCfg.values())+1): # if dt >= timeCfg[i]['NeedTime']: # less += 1 # dt -= timeCfg[i]['NeedTime'] for i in xrange(1, lottoryNum + 1): if dt >= timeCfg[str(i)]: less += 1 dt -= timeCfg[str(i)] less -= lastLottery['LotteryCount'] if less <= 0: return Gcore.error(optId, -23011001)#可抽奖次数不足 #获取抽到的奖励类型和等级 typeCfg = Gcore.getCfg('tb_cfg_act_online_type').values() typeCfg = filter(lambda dic:dic['Ratio']!=0, typeCfg)#暂时不随机到宝物和兵书 types = [] level = 3 typeValue = random.randint(2, 3)#如果等级是3则在铜钱和军资中随即一个 for i in range(0, 3): theType = common.Choice(typeCfg) for j in range(0, len(types)): if theType['TypeId'] == types[j]: level -= 1 typeValue = theType['TypeId'] break types.append(theType['TypeId']) #进行奖励 awards = Gcore.getCfg('tb_cfg_act_online_award', (typeValue, level)) award = random.choice(awards) modReward = Gcore.getMod('Reward', self.uid) award['Gain'] = modReward.reward(optId, param, award['AwardType'], award['GoodsId'], award['GoodsNum']) #更新在线奖励记录 lastLottery['AwardId'] = award['AwardId'] lastLottery['LotteryCount'] += 1 lastLottery['AwardType'] = award['AwardType'] lastLottery['GoodsId'] = award['GoodsId'] lastLottery['GoodsNum'] = award['GoodsNum'] types = [str(t) for t in types] lastLottery['LotteryInfo'] = str.join(',',types) self.mod.updateOnlineLottery(lastLottery) return Gcore.out(optId, {'LotteryInfo': lastLottery['LotteryInfo'], 'Award': award})
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 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 InsMessage(self,param={}): ''' 发送邮件 ''' import sys;reload(sys);sys.setdefaultencoding('utf8') optId=18006 toUserNickNames = param['ToUserNickNames'] #收件人昵称字符串 subject=param['Subject'] content=param['Content'] mailCfg = Gcore.loadCfg(Gcore.defined.CFG_MAIL) subjectMin = mailCfg['SubjectMin'] #主题最小字符数 subjectMax = mailCfg['SubjectMax'] #主题最大字符数 contentMin = mailCfg['ContentMin'] contentMax = mailCfg['ContentMax'] toUserMax = mailCfg['MailSendMax'] #同时发送邮件最大数量 toUserNickNames = escapeSplit(toUserNickNames) #解析昵称字符串 inexistUserNickNames = self.mod.inexistNickName(toUserNickNames) #过滤收件人 toUserIds = self.mod.getToUserId(toUserNickNames) #根据昵称,得到玩家id #最多同时发送邮件给五个玩家,最少一个 numToUserId = len(toUserIds) if numToUserId>toUserMax: #不能超过5个玩家 return Gcore.error(optId, -18006001) #过滤主题和邮件内容 subject=filterInput(subject,subjectMin,subjectMax,b_Replace=True,b_chat = True) if subject==-1: return Gcore.error(optId, -18006993)#长度不符合要求 if subject==-2: return Gcore.error(optId, -18006991)#特殊字符 content=filterInput(content,contentMin,contentMax,b_Replace=True,b_chat = True) if content==-1: return Gcore.error(optId, -18006993)#长度不符合要求 if content==-2: return Gcore.error(optId, -18006991)#特殊字符 # if not filterInput(subject,subjectMin,subjectMax) and not filterInput(content,contentMin,contentMax): # return Gcore.error(optId, -18006002) #不满足要求,长度,特殊字符,敏感字符' if self.uid in toUserIds: return Gcore.error(optId, -18006002)#不能发信息给自己 param['ToUserIds'] = toUserIds result=self.mod.sendMail(toUserIds,subject,content,2) # body ={'result':result,'inexistUserId':inexistUserId} body = {'result':result,'InexistNames':inexistUserNickNames} recordData = {'uid':self.uid,'ValType':numToUserId,'Val':1}#成就,任务记录 return Gcore.out(optId, body = body,mission=recordData)
def getWarDetail(self, StoryId): '''获取战役信息''' assert isinstance(StoryId, (int, long)) ProcessWarId = self.getUserInfo('ProcessWarId') if ProcessWarId == 0: ProcessWarId = 101 #curStoryId = self.db.out_field('tb_cfg_pve','StoryId',"WarId='%s'"%ProcessWarId) rows = self.db.out_rows('tb_cfg_pve', ['WarId', 'StoryId'], "StoryId='%s'" % StoryId) StoryWar = {} fields = [] for row in rows: fields.append('War%s' % row.get('WarId')) StoryWar[row.get('WarId')] = row.get('StoryId') sql = "SELECT count(1) AS count,WarId FROM tb_war_log WHERE UserId=%s AND RecordDate=CURDATE() Group by WarId" % self.uid rows = self.db.fetchall(sql) warlogDict = {} for row in rows: warlogDict[row['WarId']] = row['count'] GradeInfo = self.db.out_fields('tb_war_star', fields, "UserId=%s" % self.uid) if not GradeInfo: self.db.insert('tb_war_star', {"UserId": self.uid}) GradeInfo = self.db.out_fields('tb_war_star', fields, "UserId=%s" % self.uid) #print GradeInfo warInfo = [] for WarId, StoryId in StoryWar.iteritems(): WarCell = { 'warId': WarId, 'count': warlogDict.get(WarId, 0), 'star': GradeInfo.get('War%s' % WarId), 'storyId': StoryId, 'fight': 1 if WarId <= ProcessWarId else 0, #'open': 0 if WarId>ProcessWarId else 1, #'current': 1 if WarId == ProcessWarId else 0, } warInfo.append(WarCell) data = {} data['maxCount'] = self.getUserInfo('WarTimes') #data['curStoryId'] = curStoryId data['curWarId'] = ProcessWarId data['warInfo'] = warInfo sweepedTimes = self._getSweepTimes() data['sweepRestTime'] = Gcore.loadCfg(9001).get( 'sweepTimesLimit') - sweepedTimes return data
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 getWarDetail(self,StoryId): '''获取战役信息''' assert isinstance(StoryId, (int,long)) ProcessWarId = self.getUserInfo('ProcessWarId') if ProcessWarId==0: ProcessWarId=101 #curStoryId = self.db.out_field('tb_cfg_pve','StoryId',"WarId='%s'"%ProcessWarId) rows = self.db.out_rows('tb_cfg_pve',['WarId','StoryId'],"StoryId='%s'"%StoryId) StoryWar = {} fields = [] for row in rows: fields.append('War%s'%row.get('WarId')) StoryWar[ row.get('WarId') ] = row.get('StoryId') sql = "SELECT count(1) AS count,WarId FROM tb_war_log WHERE UserId=%s AND RecordDate=CURDATE() Group by WarId"%self.uid rows = self.db.fetchall(sql) warlogDict = {} for row in rows: warlogDict[row['WarId']] = row['count'] GradeInfo = self.db.out_fields('tb_war_star',fields,"UserId=%s"%self.uid) if not GradeInfo: self.db.insert('tb_war_star',{"UserId":self.uid}) GradeInfo = self.db.out_fields('tb_war_star',fields,"UserId=%s"%self.uid) #print GradeInfo warInfo = [] for WarId,StoryId in StoryWar.iteritems(): WarCell = { 'warId':WarId, 'count':warlogDict.get(WarId,0), 'star':GradeInfo.get('War%s'%WarId), 'storyId':StoryId, 'fight': 1 if WarId<=ProcessWarId else 0, #'open': 0 if WarId>ProcessWarId else 1, #'current': 1 if WarId == ProcessWarId else 0, } warInfo.append(WarCell) data = {} data['maxCount'] = self.getUserInfo('WarTimes') #data['curStoryId'] = curStoryId data['curWarId'] = ProcessWarId data['warInfo'] = warInfo sweepedTimes = self._getSweepTimes() data['sweepRestTime'] = Gcore.loadCfg(9001).get('sweepTimesLimit') - sweepedTimes return data
def getDefeaters(self, TimeStamp=None): '''获取手下败将''' TimeStamp = TimeStamp if TimeStamp else time.time() HoldConfig = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD) ExpireTime = HoldConfig["ExpireTime"] #过期时间 LimitCnt = HoldConfig["LimitCount"] #手下败将的最大个数 table = 'tb_battle_record' fields = ['PeerUID', 'PeerSID', 'PeerName', 'PeerVipLevel', 'PeerCamp', 'PeerIcon', 'PeerLevel', 'MAX(CreateTime) as CreateTime'] where = """UserId="%s" AND BattleResult=1 AND CreateTime>="%s" AND BattleType IN (1,2) GROUP BY UserId, PeerUID, PeerSID LIMIT %s""" \ % (self.uid, TimeStamp - ExpireTime, LimitCnt) res = self.db.out_rows(table, fields, where) return res
def GetBoxLogs(self, p={}): '''查询获奖记录 @param ListView: 显示列表 1:军团所有成员 2:玩家自己3:军团内两条记录 ''' optId = 15083 listView = p['ListView'] pageNum = p['PageNum'] clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId, -15083920) #军团不存在 pageSize = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxPS') logNum = self.mod.getBoxLogNum(listView, clubId) maxPage = int(math.ceil(float(logNum) / pageSize)) if 0 < maxPage < pageNum: pageNum = maxPage if pageNum < 1: pageNum = 1 offset = (pageNum - 1) * pageSize myLog = [] if logNum > 0: if listView == 1: logs = self.mod.getBoxLogList(listView, clubId, offset, pageSize) if pageNum == 1: #第二页不需显示 myLog = self.mod.getBoxLogList(2, clubId, 0, 1) elif listView == 2: logs = self.mod.getBoxLogList(listView, clubId, offset, pageSize) myLog = [logs[0]] elif listView == 3: logs = self.mod.getBoxLogList(1, clubId, 0, 2) else: logs = [] else: logs = [] return Gcore.out( optId, { 'BoxLogs': logs, 'PageNum': pageNum, 'MaxPage': maxPage, 'MyLog': myLog })
def OpenBox(self,p={}): '''开宝箱''' optId = 15082 boxType = p['BoxType'] boxCfg = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_CLUB).get('BoxCost') boxTypes = [int(i) for i in boxCfg.keys()] if boxType not in boxTypes: return Gcore.error(optId, -15082999)#参数错误 building = self.mod.getClubBuildingInfo() if building is None: return Gcore.error(optId,-15082901)#外史院建筑不存在 clubId = self.mod.getUserClubId() if not clubId: return Gcore.error(optId,-15082920)#军团不存在 #支付贡献 cost = boxCfg.get(str(boxType)) left = self.mod.payDevote(clubId,cost) # left = 1 #支付成功,开始抽奖 if left>=0: goodsCfg = Gcore.getCfg('tb_cfg_club_box',boxType) lucky = com.Choice(goodsCfg) rType = lucky.get('RewardType') goodsId = lucky['GoodsId'] goodsNum = lucky['GoodsNum'] body ={'Left':left,'RewardType':rType, 'GoodsId':goodsId, 'GoodsNum':goodsNum} equipIds = [] # if rType in [1,2,3]:#装备,道具,资源 ids = Gcore.getMod('Reward',self.uid).reward(optId,p,rType,goodsId,goodsNum) if rType==1: if isinstance(ids,list): equipIds = ids body['EIDS'] = equipIds self.mod.insertBoxLog(clubId,boxType,lucky) body['Logs'] = self.mod.getBoxLogList(1,clubId,offset=0,pageSize=2,timeLimit=False) recordData = {'uid':self.uid,'ValType':0,'Val':1}#成就,任务记录 return Gcore.out(optId,body,mission=recordData) else: return Gcore.error(optId,-15082002)# 支付失败
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 getWallBoxReward(self): '''获取城墙遗落宝箱的奖励''' CfgKey = Gcore.defined.CFG_WALL BoxAppearRatio = Gcore.loadCfg(CfgKey).get('BoxAppearRatio') from random import randint if Gcore.TEST: #开发网100机率获取 BoxAppearRatio = 100 if randint(1,100) <= BoxAppearRatio: RewardCfgList = Gcore.getCfg('tb_cfg_wall_box').values() RewardUnit = Gcore.common.Choice(RewardCfgList,count=1) #e.g. {'GoodsId': 201, 'Ratio': 40, 'GoodsNum': 1, 'RewardId': 5, 'RewardType': 2} del RewardUnit['RewardId'] del RewardUnit['Ratio'] return RewardUnit else: return {}
def getWallBoxReward(self): '''获取城墙遗落宝箱的奖励''' CfgKey = Gcore.defined.CFG_WALL BoxAppearRatio = Gcore.loadCfg(CfgKey).get('BoxAppearRatio') from random import randint if Gcore.TEST: #开发网100机率获取 BoxAppearRatio = 100 if randint(1, 100) <= BoxAppearRatio: RewardCfgList = Gcore.getCfg('tb_cfg_wall_box').values() RewardUnit = Gcore.common.Choice(RewardCfgList, count=1) #e.g. {'GoodsId': 201, 'Ratio': 40, 'GoodsNum': 1, 'RewardId': 5, 'RewardType': 2} del RewardUnit['RewardId'] del RewardUnit['Ratio'] return RewardUnit else: return {}
def _GetNextPay(self,AltarType,TimeStamp): AltarConfig = Gcore.loadCfg(CFG_BUILDING_ALTAR) AlreadyLotteryCnt = self.GetLotteryCnt({'AltarType':AltarType, 'ClientTime':TimeStamp}) AlreadyLotteryCnt = AlreadyLotteryCnt.get('body', {}).get('LotteryCount', -1) if AltarType==2: NextCostType = AltarConfig['LandCoinType'] NextCost = AltarConfig['LandTimesCost'] else: NextCostType = AltarConfig['SkyCoinType'] NextCost = min(AltarConfig['SkyTimesCost'] * (AlreadyLotteryCnt + 1),50) #打折 vipLevel = Gcore.getUserData(self.uid, 'VipLevel') discount = Gcore.getCfg('tb_cfg_vip_up',vipLevel,'Discount') discount = discount if discount else 1 NextCost = math.ceil(NextCost*discount) NextLoterryPay={'NextCostType':NextCostType,'NextCost':NextCost} return NextLoterryPay
def getDefeaters(self, TimeStamp=None): '''获取手下败将''' TimeStamp = TimeStamp if TimeStamp else time.time() HoldConfig = Gcore.loadCfg(Gcore.defined.CFG_BUILDING_HOLD) ExpireTime = HoldConfig["ExpireTime"] #过期时间 LimitCnt = HoldConfig["LimitCount"] #手下败将的最大个数 table = 'tb_battle_record' fields = [ 'PeerUID', 'PeerSID', 'PeerName', 'PeerVipLevel', 'PeerCamp', 'PeerIcon', 'PeerLevel', 'MAX(CreateTime) as CreateTime' ] where = """UserId="%s" AND BattleResult=1 AND CreateTime>="%s" AND BattleType=1 GROUP BY UserId, PeerUID, PeerSID LIMIT %s""" \ % (self.uid, TimeStamp - ExpireTime, LimitCnt) res = self.db.out_rows(table, fields, where) return res
def clearWallDefense(self): '''清理已损坏的防御工事''' where = "LifeRatio=0 AND UserId=%s" % self.uid CfgKey = Gcore.defined.CFG_WALL DefenseCleanReturn = Gcore.loadCfg(CfgKey).get('DefenseCleanReturn') sql = "SELECT SUM(MakeCost*%s) AS CleanReturnTotal FROM %s WHERE %s" \ %(DefenseCleanReturn,self.tb_wall_defense(),where) row = self.db.fetchone(sql) if row: CoinValue = row['CleanReturnTotal'] else: CoinValue = 0 if CoinValue: self.db.delete(self.tb_wall_defense(), where) return CoinValue
def recoverActPoint(self, changePoint=0, flag=1): '''恢复行动力 changePoint:要增加或减少的数 flag: 1增加 0减少 ''' row = self._lastActRecord() #没记录就是 {} if row: MaxPoint = Gcore.getCfg('tb_cfg_action_point', self.getUserLevel(), 'ActPoint') nowtime = Gcore.common.nowtime() if row['ActPoint'] >= MaxPoint: #剩余点数超过最大值 不开始累积时间 ! AccuTime = 0 ActPoint = row['ActPoint'] print '购买+剩余点数超过最大值 不开始累积时间 !' else: PerIncrTime = Gcore.loadCfg(9101).get('ActPointRecoverTime', 1200) if Gcore.TEST and self.uid in [1001, 43953]: PerIncrTime = testPerIncrTime AccuTime = row['AccuTime'] + (nowtime - row['LastWarTime']) incrTimes = AccuTime // PerIncrTime #回复一点需要多长时间 20分钟 if incrTimes: AccuTime = AccuTime % PerIncrTime print 'recoverActPoint.上次剩余', row['ActPoint'] print 'recoverActPoint.至已经恢复了', incrTimes ActPoint = row['ActPoint'] + incrTimes if ActPoint >= MaxPoint: ActPoint = MaxPoint AccuTime = 0 if flag: ActPoint += changePoint else: ActPoint -= changePoint d = { 'ActPoint': ActPoint, 'LastWarTime': nowtime, 'AccuTime': AccuTime } self.db.update('tb_war_action', d, 'UserId=%s' % self.uid) row['ActPoint'] = ActPoint row['LastWarTime'] = nowtime row['AccuTime'] = AccuTime return row #返回新的记录